'this'在原型函数中的函数中 [英] 'this' in function inside prototype function
问题描述
我基本上有一个对象,通过其原型扩展了一个函数。在该函数内部,存在另一个函数,但是当在这个嵌套函数中使用 this
时,它似乎不是引用该对象,而是函数。
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.
例如,
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
this.foo
不是引用123值,而是未定义,因为这是指嵌套函数,其中不存在 foo
。如何从嵌套函数中访问123值?
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?
推荐答案
sampleObject.prototype.getFoo = function() {
var me = this;
var nested = function() {
return me.foo;
}
return nested;
}
通过保存的值
在局部变量中,它使它明确地成为该函数和所有嵌套函数作用域的词法上下文的一部分。因此,在调用嵌套时,该内部函数将具有自己的范围(它自己的此
值),但它仍然可以引用变量mein封闭范围。
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.
这篇关于'this'在原型函数中的函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!