我基本上有一个对象,通过它的原型扩展了一个函数.在该函数内部,存在另一个函数,但是当this在这个嵌套函数中使用时,它似乎不是引用对象,而是函数.
例如,
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
Run Code Online (Sandbox Code Playgroud)
在this.foo不参考123的值,但是未定义,因为这指的是嵌套函数,其中没有foo存在.如何从嵌套函数中访问123值?
Poi*_*nty 36
sampleObject.prototype.getFoo = function() {
var me = this;
var nested = function() {
return me.foo;
}
return nested;
}
Run Code Online (Sandbox Code Playgroud)
通过保存this局部变量的值,可以使它明确地成为该函数和所有嵌套函数作用域的词法上下文的一部分.因此,在对"嵌套"的调用中,该内部函数将具有其自己的范围(它自己的this值),但它仍然可以引用封闭范围中的变量"me".
这方面的常见工作是使用闭包
sampleObject.prototype.getFoo = function() {
var _this = this;
var nested = function() {
return _this.foo;
}
return nested();
}
Run Code Online (Sandbox Code Playgroud)
一些库添加了自动化方法
在您的示例中,"this"指的是窗口对象,因为在调用嵌套函数时没有指定另一个上下文,并且因为window.foo未定义而导致您失败.
您可以通过3种方式解决此问题.
sampleObject.prototype.getFoo = function() {
var _this = this;
var nested = function() {
return _this.foo;
}
return nested();
}
Run Code Online (Sandbox Code Playgroud)
sampleObject.prototype.getFoo = function() {
var nested = function() {
return this.foo;
}.bind(this);
return nested();
}
Run Code Online (Sandbox Code Playgroud)
SampleObject.prototype.getFoo = function() {
var nested = function() {
return this.foo;
};
return nested.call(this);
}
Run Code Online (Sandbox Code Playgroud)
使用箭头功能。自ECMAScript 6起可用:
var sampleObject = function() {
this.foo = 123;
}
sampleObject.prototype.getFoo = function() {
var nested = () => { // Changed this line.
return this.foo;
}
return nested();
}
var test = new sampleObject();
window.alert(test.getFoo());Run Code Online (Sandbox Code Playgroud)
这是箭头功能的主要优点之一。您的情况在以下部分中进行了描述:的无约束力this。引用指出:
在使用箭头函数之前,每个新函数都定义了自己的
this值箭头函数不会创建自己的this上下文,因此this具有原始上下文的含义。
| 归档时间: |
|
| 查看次数: |
35251 次 |
| 最近记录: |