Reputation: 14774
I was having issues in my object literal using this
, but when changing to the name of the object variable itself, my problems went.
When using this, I was getting a 'myFunction' is not a function error.
Should I be doing this:
var app = {
init: function() {
this.myFunction();
},
myFunction: function() {
return "Hello world!";
}
};
Or, this?
var app = {
init: function() {
app.myFunction();
},
myFunction: function() {
return "Hello world!";
}
};
What is the correct way to do this?
This particular example is a very simplified version of my problem and may not reproduce the same issues, but it's the same general pattern I was following, where functions would call each other using this
.
Thanks, Michael.
Upvotes: 0
Views: 42
Reputation: 4354
In javascript this
changes depending on how the function is called. This problem is often gotten around by creating a variable named self
which is assigned the value of this
at a stage when you know positively the value of this
var app = {
self: this,
init: function() {
self.myFunction();
},
myFunction: function() {
return "Hello world!";
}
};
Upvotes: 0
Reputation: 2276
in your first code this refers and app refers same. In my point of view I can suggest
var app = {
init: function() {
app.myFunction();
},
myFunction: function() {
return "Hello world!";
}
};
this code for better understanding.
Upvotes: 0
Reputation: 1074148
What is the correct way to do this?
Both are correct, depending on what you're trying to achieve.
If you're only ever going to have one of these and you're not going to copy those methods to any other objects (which you can do in JavaScript), then using app
probably makes more sense.
My guess is that the problem you were having when you were using this
was that you'd done something like this:
somethingThatAcceptsACallback(app.init);
or
someElement.onclick = app.init;
...and when init
was called, it couldn't call myFunction
. That's because in JavaScript (for now), the way this
is set mostly depends on how a function is called, not where the function is defined. In both of the above cases, although a reference to the function is given to the other code, when the other code calls it, it doesn't do anything to set this
to app
.
You can use ES5's Function#bind
(which can be shimmed on IE8 and older) to create functions that, when called, call the original function with the correct this
value:
somethingThatAcceptsACallback(app.init.bind(app));
or
someElement.onclick = app.init.bind(app);
But again, if app
is a one-off, just using app
within your functions is fine.
More about this
(on my blog):
Upvotes: 3