how to call parent constructor?

后端 未结 5 366
感动是毒
感动是毒 2020-12-23 17:20

Let\'s say I have the following code snippet.

function test(id) { alert(id); }

testChild.prototype = new test();

function testChild(){}

var instance = new         


        
5条回答
  •  生来不讨喜
    2020-12-23 17:46

    JS OOP ...

    // parent class
    var Test = function(id) {
        console.log(id);
    };
    
    // child class
    var TestChild = function(id) {
        Test.call(this, id); // call parent constructor
    };
    
    // extend from parent class prototype
    TestChild.prototype = Object.create(Test.prototype); // keeps the proto clean
    TestChild.prototype.constructor = TestChild; // repair the inherited constructor
    
    // end-use
    var instance = new TestChild('foo');
    

提交回复
热议问题