这是在 JavaScript 中实现方法覆盖的好/安全的跨浏览器方式吗?:
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;
}
我也可以写:
Employee.prototype.sayHi = function()
{
return Person.prototype.sayHi() + " I'm a " + this.position;
}
但是对于这个解决方案,我指的是直接方法,或者
Employee.prototype.sayHi = function()
{
return this.__proto__.sayHi() + " I'm a " + this.position;
}
但这一个很糟糕,而且不是跨浏览器。
编辑:我假设 Object.create 是跨浏览器,因为我可以使用 shim