0

I know that javascript always passes objects by reference. But It doesn't work if I try to return as a result of copying reference like this :

class TestClass {
    constructor(){
        this._name = "this is in the TestClass";
        this._calclsObj = new CalCls(this);
    }
    calltest(subClass){
        subClass = this._calclsObj; //here, it does nothing. 
    }
    say(){
        console.log(this._name);
    }
}

class CalCls {
    constructor(passedClass){
        this._passedClass = passedClass;
        this._passedClass._name = "This is in the Subclass";
    }
    say(){
        console.log(this._passedClass._name);
    }
}

let parent = new TestClass();
let child = {};
parent.calltest(child);
child //Object {}  : nothing has assigned.

I tried subClass.__proto__ = this._calclsObj; and Object.assign. But That doesn't copy the reference of parent._calclsObj. How can I assign parent._calclsObj to child itself by the reference?

Peter
  • 301
  • 4
  • 17
  • 1
    Possible duplicate of [Does Javascript pass by reference?](https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference) – Rainbow Oct 27 '18 at 12:48
  • Thank you for letting me know, but I just edited why it is different from that question. I need to make `child` as `parent._calclsObj`, not as a property of `child` – Peter Oct 27 '18 at 13:08
  • 1
    Since we can modify an object why not inside `calltest()` do this `subClass.calclsObj = this._calclsObj;` then use it like this `child.calclsObj` – Rainbow Oct 27 '18 at 13:15
  • Oh...right. just as simple as that! Thank you :) I just have to expect. I guess there is no way to do this other than just making a property. – Peter Oct 27 '18 at 13:17

0 Answers0