[英]Node.js - Pass context through to nested objects in function properties
I need to make a cleanly name-spaced module in Node.js, break it up into sub-modules via require()
and pass the root context/scope all the way to the methods in the name-spaces. 我需要在Node.js中创建一个干净的命名空间模块,通过
require()
将其分解为子模块,并将根上下文/作用域一直传递到命名空间中的方法。
// index.js
var SDK = function(data){
this.data = data;
};
SDK.prototype.Utilities = require('./utilities');
module.exports = function(data) {
return new SDK(data);
};
// utilities.js
module.exports = {
callAPI: function() {
console.log(this.data);
}
};
// Use-case (somewhere in the node.js app...)
var SDK = require('./index')("this is some data");
SDK.Utilities.callAPI();
// Should return "this is some data"
For example: 例如:
this
in SDK
needs to be accessible in SDK.Utilities.callAPI();
this
在SDK
需要在访问SDK.Utilities.callAPI();
, like below. ,如下所示。
Utilities
is the name-space I'm referring to. Utilities
是我所指的名称空间。
I'm aware of javascript bind()
and call()
techniques, but I'm not sure how to use them in this particular case. 我知道javascript
bind()
和call()
技术,但不确定在这种特殊情况下如何使用它们。
You should use apply or
call
您应该使用申请或
致电
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
these run the function with the given this scope.
这些运行与给定此范围内的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.