如何通过JS将值传递给对象方法并复制以返回

时间:2018-10-27 12:24:22

标签: javascript

我知道javascript总是通过引用传递对象。但是如果我由于复制这样的引用而尝试返回,则不起作用:

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.

我尝试了subClass.__proto__ = this._calclsObj;Object.assign。但这不会复制parent._calclsObj的引用。如何通过引用将parent._calclsObj本身分配给child

0 个答案:

没有答案