2016-07-31 45 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