在一个函数中的一个对象中的“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文档说,在一个对象的函数中这是指对象。 然后我会期望console.log(this.config)
引用require'd config模块。 相反,目前还不清楚this
最终是指什么,除了它没有“configuration”属性。
显然有一个范围正在发生变化,但我不知道在哪里。 forEach? 我试图只是console.log(this)
,但我找回了一个我无法破译的巨大对象。
我不明白为什么configuration超出了这个function的范围。 这是怎么回事?
它是undefined
因为函数中的默认值是全局对象。
要修复它,请将对象作为第二个parameter passing给.forEach()
this.agencies.forEach( function(agency) { console.log(this.config) }, this) // ^---sets the `this` value
this
工作的方式是由函数的调用决定的。 因为.forEach()
不知道callback中的this
值是什么,所以它将它保留在默认值(全局对象)中,或者在严格模式下undefined
。
通过传递第二个参数,你告诉它手动将它设置为你提供的任何东西。
它是如何实现的(或者你怎么做到的)是使用函数的.apply()
或.apply()
方法来调用一个函数。
myFunction.call({foo:"bar"});
现在myFunction
将被调用{foo:"bar"}
对象设置为它的this
值。
上下文切换发生在循环中,因为在里面我相信这是“机构”
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?? } } } }
函数中的值取决于创build和调用的情况。 当你使用forEach
,你传递一个匿名函数作为第一个参数,它有自己的块范围, this
是指。
在函数中有几种方法来控制这个值。 您可以在父作用域中创build一个本地引用,通过closures可以访问它:
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)) }
…或者您可以将上下文作为第二个parameter passing给forEach
并让引擎为您绑定范围:
getRoutes: function(callback) { var API = "/api/route/"; var me = this; this.agencies.forEach( function(agency) { console.log(this.config); }, this); }
文档
这个值取决于调用函数的方式。
这是它的function:
function(agency) { console.log(this.config); //Returns undefined?? }
这是作为一个论据通过agencies.forEach
。 agencies
是一个数组,所以我们可以看一下文档 :
如果提供了一个thisArg参数给forEach,它将被调用时传递给callback函数,用作它的这个值。 否则,未定义的值将被传递以用作其值。
所以this
是undefined
。
按照上面的文档,你可以传入不同的值。
this.agencies.forEach( function(agency) { console.log(this.config); //Returns undefined?? }, this );
在这种情况下,你可以使用闭包。 config
(从var config = require('./config');
)仍然在范围内。 所以只需使用config
而不是this.config
。