我对节点模块中this
的行为感到非常困惑。 以下是相关片段:
module.exports = function(environment) {
var config = require('./config');
return {
config: config,
agencies: ["string1", "string2"],
getRoutes: function(callback) {
var API = "/api/route/";
this.agencies.forEach( function(agency) {
console.log(this.config); //Returns undefined??
}
}
}
}
查看 MDN 文档说,对象中函数中的this
引用对象。 然后我希望console.log(this.config)
引用所需的配置模块。 相反,目前尚不清楚this
最终指的是什么,除了它没有"配置"属性。
地方正在发生范围变化,但我不确定在哪里。 各为? 我试图console.log(this)
,但我找回了一个我无法破译的巨大物体。
我不明白为什么配置超出了此功能的范围。 这是怎么回事?
之所以undefined
,是因为函数中 this
的默认值是全局对象。
若要修复它,请将对象作为第二个参数传递给.forEach()
this.agencies.forEach( function(agency) {
console.log(this.config)
}, this)
// ^---sets the `this` value
this
的工作方式是它由函数的调用方式决定。由于.forEach()
不知道回调中this
值需要什么,因此它会将其保留为默认值(即全局对象),或undefined
处于严格模式。
通过传递第二个参数,您告诉它手动将this
设置为您提供的任何内容。
它如何实现这一点(或者无论如何如何做到这一点)是使用函数的.call()
或.apply()
方法调用函数。
myFunction.call({foo:"bar"});
现在,将使用设置为其this
值的{foo:"bar"}
对象来调用myFunction
。
上下文切换发生在循环中,因为内部我相信这是"机构"
module.exports = function(environment) {
var config = require('./config');
return {
config: config,
agencies: ["string1", "string2"],
getRoutes: function(callback) {
var API = "/api/route/";
var self = this;
this.agencies.forEach( function(agency) {
console.log(self.config); //Returns undefined??
}
}
}
}
> 函数中this
的值取决于创建和调用它的环境。当你使用 forEach
时,你会向它传递一个匿名函数作为第一个参数,该函数有自己的块作用域,this
引用。
有几种方法可以控制函数中this
的值。您可以在父作用域中创建本地引用,该引用可通过闭包访问:
getRoutes: function(callback) {
var API = "/api/route/";
var me = this; // local reference to the current scope
this.agencies.forEach( function(agency) {
console.log(me.config); // accessed via closure
});
}
。您可以bind
函数:
getRoutes: function(callback) {
var API = "/api/route/";
this.agencies.forEach( function(agency) {
console.log(this.config);
}.bind(this))
}
。或者,您可以将上下文作为第二个参数传递给forEach
,并让引擎为您绑定范围:
getRoutes: function(callback) {
var API = "/api/route/";
var me = this;
this.agencies.forEach( function(agency) {
console.log(this.config);
}, this);
}
文档
-
forEach
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach -
bind
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
this
的值取决于它所在的函数的调用方式。
这是它所在的函数:
function(agency) {
console.log(this.config); //Returns undefined??
}
它作为参数传递给agencies.forEach
. agencies
是一个数组,因此我们可以查看文档:
如果向 forEach 提供了 thisArg 参数,则在调用时将传递给回调,以用作其 this 值。 否则,将传递未定义的值以用作其此值。
所以this
undefined
.
您可以根据上述文档为this
传入不同的值。
this.agencies.forEach(
function(agency) {
console.log(this.config); //Returns undefined??
},
this
);
在这种情况下,您可以只使用闭包。 config
(从var config = require('./config');
)仍将在范围内。所以只需使用config
而不是this.config
。