简体   繁体   English

如何将子对象划分为父对象?

[英]How to scope child to parent object?

I got following code: 我得到以下代码:

define(function() {

    var core = function() {};
    var module;

    core.prototype.module = {
      setModule: function(name) {
        this.module = name;
        module = name;
      }
    };

    core.prototype.sandbox = {
      getModules: function() {
          // will throw undefined
          console.log(this._module);
          // will maybe not throw an error?
          console.log(modules);
      }
    };

});

define(['kernel'], function(Kernel) {
    var sampleCore = new Core();
    sampleCore.setModule('test');
    sampleCore.getModules();
});

As you see I can't access the other namespace with this approach. 如您所见,我无法使用这种方法访问其他名称空间。 Is there another way to access this.module somehow? 还有另一种方式可以访问this.module吗?

Regards 问候

How about setting a parameter for the object?: 如何为对象设置参数?

core.sandbox = {
    register: function(obj, name) {
        console.log( obj.module );
    }
};

var a = new core.module.load(/* ..., .... */);

core.sandbox.register( a );

Use core.module._modules 使用core.module._modules

core.sandbox = {
  register: function(name) {
      var modules = core.module._modules;
  }
};

As I've said in a comment, maybe you can add a that variable to the core object, so that the other functions have something common to get a hold on? 就像我在评论中说的那样,也许您可​​以向核心对象添加一个那个变量,以便其他功能具有共同的特性来保持?

define(function() {
    var core = function() {
    var that = this;
    };
    var module;
    core.prototype.module = {
      setModule: function(name) {
        that.module = name;
        module = name;
      }
    };

    core.prototype.sandbox = {
      getModules: function() {
          console.log(that.module);
      }
    };

});

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

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