如何访问导出模块上的父变量?
function ThunderClient(key){//my class
this.key = key //i want have access to this variable
}
ThunderClient.prototype.users = require('./modules/users')(route_rest,this.key); //this.key are key of ThunderClient
ThunderClient.prototype.address = require('./modules/address')(route_rest,this.key);//this.key are key of ThunderClient
require('./modules/address')(route_rest,this.key);
this.key是ThunderClient的一个密钥(在构造中,我填充这个变量)。在我的模块上,我希望用户可以访问ThunderClient的this.key,但如果我在require上使用"this.key"不起作用,我怎么能这样做?
将导入的函数放在顶部:
var users = require('./modules/users');
var address = require('./modules/address');
然后只包装那些导入的函数:
ThunderClient.prototype.users = function(){ return users(route_rest, this.key); }
ThunderClient.prototype.address = function(){ return address(route_rest, this.key); }
如果您希望在创建时指定特定于实例的users
,则需要将它们添加到构造函数中而不是原型中创建的实例中。
function ThunderClient(key){
this.key = key;
this.users = users(route_rest, this.key);
this.address = address(route_rest, this.key);
}
行ThunderClient.prototype.users = require('...')
和ThunderClient.prototype.address
在全局范围内执行,而不是在ThunderClient
模块的实例中执行。
例如:ThunderClient.prototype.users = require('./modules/users')(route_rest,this.key);
在Web浏览器中,this
将是window
,这意味着您正在检查window.key
,而不是执行以下操作:
ThunderClient.prototype.getKey = function() {
return this.key; // here, 'this' is definitely our module instance
};
var client = new ThunderClient('abc');
console.log(client.getKey); // abc