2016-07-31 44 views
0

我需要訪問,我在我的index.js定義從被稱爲與需要()設置公共變量的node.js

Index.js static.js可變

function API() { 
    var self = this 
    self.init = function(apikey, region, locale) { 
     //Some stuff 
     self.region = region 
     self.locale = locale 
     self.apikey = apikey 

     self.static = require('./static').static 

    } 

} 
module.exports = new API(); 

靜.js文件

module.exports = { 
    static: { 
     someFunction: function(someParameters) { 
      //Need to access to self.region, self.locale and self.apikey 
     }, 
     otherFunction: function(someParameters) { 
      //Need to access to self.region, self.locale and self.apikey 
     } 
    } 

我的問題是使用區域,語言環境和apikey從static.js文件

Test.js var api = require('./ index.js');

api.init('myKey', 'euw', 'en_US') 
console.log(api); 

做的是:

RiotAPI { 
    region: 'euw', 
    locale: 'en_US', 
    apikey: 'myKey', 
    static: { someFunction: [Function], otherFunction: [Function] } 
} 

這是好的,但是當我調用someFunction()與良好的參數,它告訴我,self.region(和其他人我猜)是沒有定義

回答

0

您需要將static.js中的方法放在API實例的頂層。

var static = require('./static').static 
function API() { 
    // constructor 
} 

API.prototype.init = function(apikey, region, locale) { 
    //Some stuff 
    this.region = region 
    this.locale = locale 
    this.apikey = apiKey 
} 
Object.assign(API.prototype, static) 
module.exports = new API(); 

然後在你的靜態方法中引用this.region等。

+0

爲什麼不使用Object.assign()將屬性從一個對象複製到另一個對象? – jfriend00

+0

@ jfriend00是的,你也可以做到這一點。 – idbehold

+0

@ jfriend00我根據您的建議編輯了我的答案。 – idbehold