简体   繁体   English

Node.js-将上下文传递给函数属性中的嵌套对象

[英]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(); thisSDK需要在访问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()技术,但不确定在这种特殊情况下如何使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM