"this"在函数中的对象函数中

ABM*_*gil 1 javascript node.js

我对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??
            }
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

望着这个MDN文件说,一个this在对象的功能是指该对象.然后我希望console.log(this.config)引用require'd配置模块.相反,它不清楚this最终指的是什么,除了它没有"配置"属性.

很明显,某个地方会有范围变化,但我不确定在哪里.forEach?我试着去console.log(this),但是我找回了一个我无法解读的巨大物体.

我不明白为什么配置超出了这个功能的范围.这是怎么回事?

coo*_*ter 7

这是undefined因为this函数中的默认值是全局对象.

要修复它,请将对象作为第二个参数传递给 .forEach()

this.agencies.forEach( function(agency) {
    console.log(this.config)
}, this)
//   ^---sets the `this` value
Run Code Online (Sandbox Code Playgroud)

该方法this的工作原理是,它是由确定如何调用该函数.因为.forEach()不知道你想要什么this对回调中的值,它将它保留为默认值,即全局对象,或者undefined在严格模式下.

通过传递第二个参数,您告诉它手动设置this为您提供的任何内容.

如何实现这一点(或者无论如何都可以这样做)是使用函数.call().apply()方法调用函数.

myFunction.call({foo:"bar"});
Run Code Online (Sandbox Code Playgroud)

现在myFunction将以{foo:"bar"}对象设置为其this值来调用.