javascript - 如何访问 require 模块节点上的父变量

标签 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

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/

相关文章:

javascript - 如何从 javascript 调用 AngularJS 函数?

javascript - 是否可以在函数作用域而不是全局作用域下运行通过函数构造函数创建的函数

javascript - 在 JavaScript 中将 JSON 字符串解析为特定的对象原型(prototype)

javascript - 如何访问 jQuery 回调函数中的属性?

c - NGINX 中的模块链接

javascript - Angular promise 返回 __proto__

javascript - 如何在 Highcharts 中显示错误消息?

C++:实例化对象

module - FORTRAN 95 : is it possible to share a module without sharing the source code?

module - 安塞 bool : how to pass multiple commands