简体   繁体   中英

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):

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. In my server.js, I made an instance of objOne and objTwo:

objOne = new objOne(a, b);
objTwo = new objTwo(c);

How do I make objOne available for 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: 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.

Is there a more elegant way of making funcA available in funcB without associating objOne with objTwo?

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). You can give a look at Danf for example or google it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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