2016-03-28 72 views
0

我想重構一個大的JS代碼庫從單個文件到多個文件中的多個類。我無法訪問我認爲應該能夠訪問的變量。我必須誤解JavaScript對象/ NodeJS模塊/ exports/imports /引用'this'。NodeJS和ES6類實例中可變的可見性

module.exports = HeatMap; 
class HeatMap { 
    constructor(ai, ...) { 
     this.ai = ai; 
     ... 
    } 
    ... 
} 

我修改ai.js:

我開始之前,一切按的EcmaScript 6類語法在裏面塊module.exports = function Ai() { ...

我創建的文件heatMap.js文件ai.js導入HeatMap類,實例化它,並將該對象的引用傳遞給ai對象,以便熱圖可以訪問其變量。

const HeatMap = require("heatMap.js"); 
module.exports = function Ai() { 
    var ai = this; 
    var currentRound = ... 
    ... 
    function bookKeeping(...) { 
     heatMap = new HeatMap(ai,...); 
     ... 
    } 
    ... 
} 

嘗試訪問currentRound內部熱圖與this.ai.currentRound收率:

未解決的可變currentRound。

爲什麼? 「this」應該引用實例化的heatMap對象,「ai」應該引用ai對象,並且ai對象具有可變currentRound。使這項工作的一種方法是將所有變量作爲參數傳遞給函數調用,但其中有很多,所以它不會是一個乾淨的解決方案。

+1

*「」ai「應該引用ai對象」*「,但該對象是否有屬性'currentRound'?在你的例子中,你所做的只是創建一個*局部變量*'currentRound',而不是一個屬性。也許你打算做'this.currentRound = ...'? –

回答

2

鑑於HeatMap定義:

module.exports = HeatMap; 

function HeatMap(ai) { 
    console.log(ai.currentRound); 
} 

而且AI定義:

module.exports = AI; 
const HeatMap = require('HeatMap'); 

function AI() { 
    this.currentRound = 0; 
} 

AI.prototype.bookKeeping = function bookKeeping() { 
    const heatMap = new HeatMap(this); 
} 

您應該看到印在從AI實例調用bookKeeping()0

我不使用ES2015類,但從我看到的,你的範圍是錯誤的。您的currentRound變量在本地作用域爲AI函數,並未以任何方式公開(在您提供的代碼段中)。因此,當您將AI的實例傳遞給HeatMapcurrentRound可用於AI構造函數公開的方法,但不可用於HeatMap函數本身。