1

サーバーからの関数のコールバックとして、モジュールに属するメソッドを使用しています。

このメソッドから、モジュール ( MyArray) にカプセル化された配列にアクセスする必要があります。

this元の関数(someFunction私の例では)を参照しているため、使用できません。that: thisしかし、この場合に機能を使用できない理由がわかりません( that is undefined)。

MyModule.js

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

サーバー.js

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

2 に答える 2

1

this.MyArray動作します。

MyModule.testthisに等しいにバインドされていますmodule.exports

モジュール内でローカル変数を使用することもできます。

MyModule.js

var MyArray = [];

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

を使用することもできますmodule.exports.MyArray

于 2013-03-02T01:43:09.163 に答える
0

を使用bindして、必要な関数をその関数にバインドしthisて、コールバックとして使用されている場合でも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);
于 2013-03-02T02:49:39.397 に答える