Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Classical Inheritance calling parent

I want to call the super method in an extended javascript 'class' by applying classical inheritance.

function Person(name, age) {
    this._name = name;
    this._age = age;
}
Person.prototype.exposeInfo = function() {
    alert(this._name + ' - ' + this._age);    
}

function Employee(name, age) {
    this.parent.constructor.call(this, name, age);
}
Employee.prototype.exposeInfo = function() {
    alert('Call employee');
    this.parent.exposeInfo();    
}

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.parent = Person.prototype;


var p1 = new Person('John Doe', 30);
p1.exposeInfo();

var p2 = new Employee('John Foobar (empl.)', 35);
p2.exposeInfo();

JS Fiddle

The problem is that the method is not being called in the extended class, but only in the parent (Person).

like image 387
barry Avatar asked Feb 27 '26 06:02

barry


1 Answers

That's because the overriding exposeInfo is being attached to the former prototype object, which is then replaced:

Employee.prototype = Object.create(Person.prototype);

You'll want to reverse the order, attaching methods after creating the prototype:

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.parent = Person.prototype;

Employee.prototype.exposeInfo = function() {
    // ...
}

You'll also need to use .call() or .apply() with exposeInfo as you did with the constructor:

Employee.prototype.exposeInfo = function() {
    alert('Call employee');
    this.parent.exposeInfo.apply(this, arguments);    
}

Otherwise, the value of this will be determined by the last member operator:

// so, calling:
this.parent.exposeInfo();

// is equivalent to:
alert(this.parent._name + ' - ' + this.parent._age);
like image 174
Jonathan Lonowski Avatar answered Feb 28 '26 18:02

Jonathan Lonowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!