如何在require模块节点

时间:2015-12-30 17:39:45

标签: javascript object module parent require

我如何在导出模块上访问父变量?

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
  

要求(” ./模块/地址)(route_rest,this.key);

this.key是ThunderClient的关键(在构造中我填充此变量)。 在我的模块用户,我想要访问ThunderClient的this.key,但如果我使用“this.key”上的请求不起作用,我怎么能这样?

2 个答案:

答案 0 :(得分:0)

将导入的功能置于顶部:

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);
}

答案 1 :(得分:0)

ThunderClient.prototype.users = require('...')ThunderClient.prototype.address正在全局范围内执行,而不是ThunderClient模块的实例。

例如:ThunderClient.prototype.users = require('./modules/users')(route_rest,this.key); 在网络浏览器中,thiswindow,这意味着您正在检查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