【问题标题】:Js: How to reference> property constructor from another constructorJs:如何从另一个构造函数引用>属性构造函数
【发布时间】:2017-05-27 20:45:30
【问题描述】:

我想从Constructor2 引用Constructor1 (property1) 中的一个属性 我想,这样做没问题...还是应该将constructor2 嵌套在constructor1 中?

var Constructor2 = function() {
    this.method2 = function() {
        // how to reference Constructor1.property ???
    };
};

var Constructor1 = function() {

    this.property1 = true;
    this.property2 = false;

    this.method1 = new Constructor2();
};

var inst = new Constructor1();

inst.method1.method2();

【问题讨论】:

  • GForceConstructor2一样吗?
  • 您需要将inst 作为参数传递给method2,或者从method1 的构造函数中创建对它的引用。
  • 该方法根本不在构造函数上。它在它返回的实例上。 this 不是指构造函数,而是调用new Constructor1() 时将返回的对象。
  • 是的,我弄错了 GForce is Constructor2

标签: javascript object constructor


【解决方案1】:

这似乎是委托模式的一个示例。

您的“类”Constructor1 将其部分逻辑委托给“类”Constructor2。

Constructor2 需要访问委托人的属性,这可以通过将委托人的实例传递给委托人来完成:

var Constructor2 = function(delegator) {
    this.delegator = delegator;
    this.method2 = function() {
        console.log(delegator.property1);
    };
};

var Constructor1 = function() {

    this.property1 = true;
    this.property2 = false;

    this.method1 = new Constructor2(this);
};

var inst = new Constructor1();

inst.method1.method2();

我认为将 Constructor1 和 Constructor2 视为类而不是构造函数会更好。我知道它们是函数并且它们用于创建对象,但通常它们会获得它们将实例化的类的名称。

【讨论】:

  • 感谢您的回答。现在我要问...这是一个好方法吗?为什么不应该把Constructor2 放在Constructor1 里面
  • 我认为,如果 Constructor2 仅作为 Constructor1 的一部分存在,那么您的建议是有道理的。
猜你喜欢
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 2010-12-15
  • 1970-01-01
  • 2014-03-12
相关资源
最近更新 更多