how to call parent constructor?

后端 未结 5 500
感动是毒
感动是毒 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:36

    You already have many answers, but I'll throw in the ES6 way, which IMHO is the new standard way to do this.

    class Parent { 
      constructor() { alert('hi'); } 
    }
    class Child extends Parent { 
      // Optionally include a constructor definition here. Leaving it 
      // out means the parent constructor is automatically invoked.
      constructor() {
        // imagine doing some custom stuff for this derived class
        super();  // explicitly call parent constructor.
      }
    }
    
    // Instantiate one:
    var foo = new Child();  // alert: hi
    

提交回复
热议问题