What is the best way to implement method overriding in JavaScript that is both effective and cross-browser compatible?
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};
Person.prototype.sayHi = function() {
return "Hi, my name is " + this.firstName;
};
function Employee(firstName, lastName, position) {
Person.call(this, firstName, lastName);
this.position = position;
};
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.sayHi = function() {
return this.constructor.prototype.sayHi() + " I'm a " + this.position;
}
I could also use:
Employee.prototype.sayHi = function() {
return Person.prototype.sayHi() + " I'm a " + this.position;
}
but with this solution I'm referring to direct method. Alternatively, I can use:
Employee.prototype.sayHi = function() {
return this.__proto__.sayHi() + " I'm a " + this.position;
}
however, this approach may not be supported across all browsers.
EDIT: Assuming Object.create is cross-browser since a shim can be used