我想从Constructor1
引用Constructor2
(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();
答案 0 :(得分:0)
这似乎是委托模式的一个例子。
你的"班级" 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视为构造函数而是作为类。我知道它们是函数,它们用于创建对象,但通常它们会获得它们将要实例化的类的名称。