设置公共变量node.js

时间:2016-07-31 00:07:53

标签: javascript node.js

我需要访问我在static.js中的index.js中定义的变量,该变量使用require()

调用

Index.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();

Static.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
        }
    }

我的问题是使用static.js文件中的region,locale和apikey

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(以及我想的其他人)没有被定义

1 个答案:

答案 0 :(得分: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等。