我如何访问导出模块上的父变量?
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); }
如果您想在创建时分配特定于实例的用户
,那么您需要将它们添加到构造函数内而不是原型(prototype)中创建的实例中。
function ThunderClient(key){
this.key = key;
this.users = users(route_rest, this.key);
this.address = address(route_rest, this.key);
}
关于javascript - 如何访问 require 模块节点上的父变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34534384/