[英]passing objects to other objects in javascript?
I have an object objOne and another objTwo, defined thus (please note the comment where I have the question): 我有一个这样定义的对象objOne和另一个objTwo(请注意我有问题的地方的注释):
function objOne(varA, varB) {
this.varA = varA;
this.varB = varB;
}
objOne.prototype = {
constructor: objOne,
funcA: function() {
//do stuff
}
}
function objTwo(varA) {
this.varA = varA;
}
objTwo.prototype = {
constructor: objTwo,
funcB: function() {
//do stuff
//NEED TO USE objOne's instance's funcA here
}
}
I am developing in NodeJS. 我正在用NodeJS开发。 In my server.js, I made an instance of objOne and objTwo:
在我的server.js中,我创建了objOne和objTwo的实例:
objOne = new objOne(a, b);
objTwo = new objTwo(c);
How do I make objOne available for objTwo? 如何使objOne可用于objTwo? This way is the only way that worked:
这种方法是唯一可行的方法:
//modifed objTwo constructor:
function objTwo(varA, objOne) {
this.varA = varA;
this.objOne = objOne;
}
then in the definition for funcB: 然后在funcB的定义中:
funcB: function() {
this.objOne.funcA();
//do other stuff
}
but this has the nasty side effect of making my objTwo have objOne as one of its members, which I do not want. 但这有使我的objTwo具有objOne作为其成员之一的讨厌的副作用,我不希望这样做。
Is there a more elegant way of making funcA available in funcB without associating objOne with objTwo? 在不将objOne与objTwo关联的情况下,是否有更优雅的方法可以使funcA在funcB中可用?
Thank you. 谢谢。
There is a really simple way: 有一种非常简单的方法:
function objOne(varA, varB) {
this.varA = varA;
this.varB = varB;
}
objOne.prototype = {
constructor: objOne,
funcA: function() {
//do stuff
}
}
function objTwo(varA) {
this.varA = varA;
}
objTwo.prototype = {
constructor: objTwo,
funcB: function(objOne) { // Pass objOne at the function call
//do stuff
//NEED TO USE objOne's instance's funcA here
}
}
This is the only way I see anyway. 无论如何,这是我唯一的见解。
If you want to use OOP in javascript in a more professional and confortable environment (classes, inheritance, interfaces, dependency injection, ...) I would suggest you to use a framework helping you to really handle OOP (because native javascript is a bit light on the subject). 如果您想在更专业,更舒适的环境中使用javascript中的OOP(类,继承,接口,依赖项注入等),我建议您使用一个框架来真正处理OOP(因为原生javascript有点照亮主体)。 You can give a look at Danf for example or google it!
您可以看一下Danf或google它!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.