我需要从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(以及其他我想的)没有被定义
I need to access to a variable that i define in my index.js from static.js which is called with 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 } }My problem is to use region, locale and apikey from the static.js file
Test.js var api = require('./index.js');
api.init('myKey', 'euw', 'en_US') console.log(api);does that:
RiotAPI { region: 'euw', locale: 'en_US', apikey: 'myKey', static: { someFunction: [Function], otherFunction: [Function] } }which is okay but when i call someFunction() with the good arguments it tells me that self.region (and the others i guess) is not defined
最满意答案
您需要将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等。
You need to put the methods from static.js at the top-level of your API instance.
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();Then reference this.region etc. in your static methods.
更多推荐
发布评论