Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call parent constructor?

Let's say I have the following code snippet.

function test(id) { alert(id); }  testChild.prototype = new test();  function testChild(){}  var instance = new testChild('hi'); 

Is it possible to get alert('hi')? I get undefined now.

like image 563
Moon Avatar asked Jul 07 '11 22:07

Moon


2 Answers

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'); 
like image 157
roylaurie Avatar answered Oct 09 '22 02:10

roylaurie


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 
like image 37
Sk606 Avatar answered Oct 09 '22 04:10

Sk606