【发布时间】:2018-11-27 20:41:54
【问题描述】:
大家下午好。
我需要知道这样的事情是否可行以及如何:
让我们假设如下示例:
function ObjectB(pFoo){
//Some object vars/properties
this.varX = '';
//Some object methods
this.methodX = function(){
//...
//HERE. is where I want to call the function/method from "my container/parent", which is an instanced ObjectA. How can I call for example, "method2()" from ObjectA?
//...
};
this.methodY = function(){
//...
console.log(this.varX);
//...
};
//Constructor time
this.varX = pFoo;
}
function ObjectA(pA, pB){
//Some object vars/properties
this.var1 = '';
this.var2 = '';
this.innerObjB = null;
//Some object methods
this.method1 = function(){
//...
this.innerObjB.methodY(); //No problem at all: calls method from it's own inner "var/property" self object.
//...
};
this.method2 = function(){
//...
this.var2 = 'trololo';
//...
};
this.method3 = function(){
//...
this.innerObjB.methodX();
//...
};
this.method4 = function(){
//...
console.log(this.var2);
//...
};
//Constructor time
this.var1 = pA;
this.var2 = pB;
this.innerObjB = new ObjectB("whatever");
}
//Runtime
var ObjA = new ObjectA("blah", "bleh");
ObjA.method1(); //prints "whatever".
ObjA.method4(); //prints "bleh".
ObjA.method3(); //calls innerObjB.methodX(), which SHOULD call ObjectA method2().
ObjA.method4(); //If previous thing were resolved, now this should print "trololo".
我怎样才能做到这一点?如何使 ObjectB 的 methodX() 调用它的“容器/父级”(不是真正的父级,因为这不是继承)ObjectA 已经实例化了 method2()?
我的想法是作为参数从对象 A 传递给对象 B,即“this”,例如:
this.innerObjB = new ObjectB("whatever", this);
这样,我将在 ObjectB 中访问“完整的 objectA”。已经实例化并且功能齐全。 但这在我的中间造成了一个深洞:这不是一种罕见的“递归”依赖吗?因为您可以再次从 B 访问 A,然后从该 A 访问 B 再一次,永远不要结束循环。所以这根本没有多大意义......
感谢您的宝贵时间。
亲切的问候,
马克。
【问题讨论】:
-
不清楚您要在这里创建什么对象模型。如果您正在合成,那么通常您不会 这样做,如果是,
ObjectB实例将需要ObjectA实例来调用其函数。ObjectB和ObjectA是什么关系? -
听起来像javascript对象继承
-
好吧不是继承。想象一下,objectA 是“House()”。在这里面,你有一个“Persons()”对象和一个“Furnitures()”对象。然后你有一些方法基本上建立了它们之间的相互关系,在 House() 对象级别,例如,方法“userSaveToCloset(u, c)”。但是,在某些时候,在 Persons() 对象内部,您可能需要调用该精确方法。并且在 Persons() 类中重新定义它不是一种选择。像这样的东西。所以你看,不是继承,而是各自概念之间的关系。
-
两个对象之间的循环引用没有任何问题。 (不,这里不涉及递归,也不会尝试无休止地遍历属性。
标签: javascript oop prototypal-inheritance circular-reference