I basically have an object, extended with a function through its prototype. Inside that function, another function exists, however when using this
in this nested function, it does not seem to refer to the object, but the function.
For example,
var sampleObject = function() {
this.foo = 123;
}
sampleObject.prototype.getFoo = function() {
var nested = function() {
return this.foo;
}
return nested();
}
var test = new sampleObject();
window.alert(test.getFoo()); // undefined
The this.foo
does not refer to the 123 value, but is undefined as this refers to the nested function, in which no foo
exists. How can I access the 123 value from the nested function?
Answer
sampleObject.prototype.getFoo = function() {
var me = this;
var nested = function() {
return me.foo;
}
return nested;
}
By saving the value of this
in a local variable, you make it explicitly part of the lexical context for that function and for all nested function scopes. Thus, on the call to "nested", that inner function will have its own scope (it's own this
value), but it can still refer to the variable "me" in the enclosing scope.
No comments:
Post a Comment