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.
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');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With