如何访问这个封装的值?

我正在使用属于一个模块的方法作为从我的服务器function的callback。

从这个方法,我需要访问模块( MyArray )encasulated一个数组。

我不能使用this因为它指的是原来的function(在我的例子someFunction )。 但我不明白为什么我不能使用that: this在这种情况下that: thisfunction( that is undefined )。

MyModule.js

 module.exports = { MyArray: [], that: this, test: functiion() { //How to access MyArray ? } }; 

server.js

 var MyModule = require('MyModule'); someFunction(MyModule.test); 

this.MyArray作品。

MyModule.test绑定到this等于module.exports

你也可以在模块中使用局部variables。

MyModule.js

 var MyArray = []; module.exports = { test: function() { // MyArray is accessible } }; 

你也可以使用module.exports.MyArray

你可以使用bind来绑定你想要的那个函数,这样即使它被用作callback函数, this也是正确的:

MyModule.js

 module.exports = { MyArray: [] }; module.exports.test = (function() { console.log(this.MyArray); // works here even when not called via MyModule.test }).bind(module.exports);