Node.js 如何访问这个封装的值?

Node.js 如何访问这个封装的值?,node.js,Node.js,我正在使用属于模块的方法作为来自服务器的函数中的回调 通过此方法,我需要访问模块中封装的阵列(MyArray) 我不能使用this,因为它引用了原始函数(在我的示例中是someFunction)。 但是我不明白为什么我不能在这种情况下使用that:this功能(未定义) MyModule.js module.exports = { MyArray: [], that: this, test: functiion() { //How to access MyArray ?

我正在使用属于模块的方法作为来自服务器的函数中的回调

通过此方法,我需要访问模块中封装的阵列(
MyArray

我不能使用
this
,因为它引用了原始函数(在我的示例中是
someFunction
)。 但是我不明白为什么我不能在这种情况下使用
that:this
功能(
未定义)

MyModule.js

module.exports = {
  MyArray: [],
  that: this,
  test: functiion() {
    //How to access MyArray ?
  }
};
var MyModule = require('MyModule');
someFunction(MyModule.test);
module.exports = {
  MyArray: []
};
module.exports.test = (function() {
  console.log(this.MyArray); // works here even when not called via MyModule.test
}).bind(module.exports);
server.js

module.exports = {
  MyArray: [],
  that: this,
  test: functiion() {
    //How to access MyArray ?
  }
};
var MyModule = require('MyModule');
someFunction(MyModule.test);
module.exports = {
  MyArray: []
};
module.exports.test = (function() {
  console.log(this.MyArray); // works here even when not called via MyModule.test
}).bind(module.exports);

这个.MyArray可以工作

MyModule.test
绑定到一个与
module.exports

您也可以只在模块内使用局部变量

MyModule.js
您还可以使用
module.exports.MyArray
这个.MyArray
可以工作

MyModule.test
绑定到一个与
module.exports

您也可以只在模块内使用局部变量

MyModule.js 您还可以使用
module.exports.MyArray
绑定到您想要的函数,以便即使将其用作回调时,
也是正确的:

MyModule.js

module.exports = {
  MyArray: [],
  that: this,
  test: functiion() {
    //How to access MyArray ?
  }
};
var MyModule = require('MyModule');
someFunction(MyModule.test);
module.exports = {
  MyArray: []
};
module.exports.test = (function() {
  console.log(this.MyArray); // works here even when not called via MyModule.test
}).bind(module.exports);
您可以使用将
this
绑定到该函数,以便即使将其用作回调,该
this
也是正确的:

MyModule.js

module.exports = {
  MyArray: [],
  that: this,
  test: functiion() {
    //How to access MyArray ?
  }
};
var MyModule = require('MyModule');
someFunction(MyModule.test);
module.exports = {
  MyArray: []
};
module.exports.test = (function() {
  console.log(this.MyArray); // works here even when not called via MyModule.test
}).bind(module.exports);

您知道从模块返回的内部函数可以通过闭包访问MyArray您知道从模块返回的内部函数可以通过闭包访问MyArray