Inheritance in javascript, variables in the “parent”

前端 未结 3 1625
隐瞒了意图╮
隐瞒了意图╮ 2020-12-30 10:45

I am doing OO javascript for the first time. I have read about inheritance and prototype and thought I had cracked it. Until I discovered this little example.



        
相关标签:
3条回答
  • 2020-12-30 11:20

    have you already tried to define this.clone_array = []; into TestObject2 instead?

    function TestObject2(data)
    {
        this.clone_array = [];
        this.__construct(data);
        this.dothings = function()
        {
            this.dosomestuff();
        }
    }
    
    0 讨论(0)
  • 2020-12-30 11:24

    Basically

    TestObject2.prototype = new TestObject(); 
    

    places a single instance of TestObject in the prototype chain of TestObject2. Thus, any instances of TestObject2 will modify the same single instance offspring property in TestObject. If you put another console.log in the construtor of TestObject you'll notice it only getting called once!

    More details to your exact problem can be found here.

    You need to call the constructor of TextObject from within the constructor of TextObject2 like this:

    function TestObject2(data)
    {
        TestObject.call( this, data);
        this.__construct(data);
        this.dothings = function()
        {
            this.dosomestuff();
        }
    }
    

    By calling the TestObject constructor function and executing it in the scope of (this is) the new TestObject2 object, it creates all elements of TestObject in TestObject2 object.

    0 讨论(0)
  • 2020-12-30 11:33

    I think

    TestObject2.prototype = new TestObject();
    

    is overriding the constructor of TestObject2.

    Try

    function TestObject2(data)
    {
        TestObject.call( this, data);
        this.__construct(data);
        this.dothings = function()
        {
            this.dosomestuff();
        }
    }
    
    
    TestObject2.prototype = new TestObject();
    TestObject2.prototype.constructor = TestObject2;
    
    0 讨论(0)
提交回复
热议问题