I'm trying my hand at using Addy Osmani's prototype pattern.
I have an object "app" and, upon a submission of a form, I'm trying to call a function inside of my init function. But it isn't console.logging...
$(document).ready(function() {
var app = {
logHello: function() {
console.log('hello');
},
initialize: function() {
$('#userlogin').on('submit', function(){
this.logHello;
return false;
});
}
}
app.initialize();
});
Where am I going wrong?
3 Answers 3
this is now referring to your jQuery on submit function, try using a context variable of this (also, you need () after you call your function):
var self = this;
$('#userlogin').on('submit', function(){
self.logHello();
return false;
});
Comments
initialize: function() {
var self=this;
$('#userlogin').on('submit', function(){
self.logHello();
return false;
});
}
this keyword changes according to the function scope, a function in another function creates a new scope ,unless it is bound to a scope somehow.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Comments
It's an issue of scope. Within the submit event handler, the this variable refers to the function's scope and not the scope of app where your logHello function resides.
Try something like this :
...
initialize: function() {
var old_scope = this; // save the scope into a local variable
$( '#userlogin' ).on( 'submit' , function() {
old_scope.logHello;
return false;
});
},
...
The variable old_scope will now contain the scope of app, so you'll be able to access all of the variable and functions that app holds.
thisrefers to the element (explicitly set by jQuery). Sothis.logHello, which would do nothing anyways because you aren't calling anything, refers to something that doesn't exist