我在JavaScript中实现了从父类继承的函数。它适用于这种风格的代码。在对象原型中定义继承
function Foo(){}
Foo.prototype = {
constructor: Foo,
name: 'foo',
tostring: function()
{
return this.name;
}
};
function Bar(){}
Bar.prototype = new Foo();
Bar.prototype.name = 'bar';
var b = new Bar();
console.log(b.tostring()); // says 'bar'
这没关系。但是我在Bar中有很多属性,我不想每次重复Bar.prototype.someProp,所以我使用了简写版本,并且它不是继承。
function Bar(){}
Bar.prototype = new Foo();
Bar.prototype = {
constructor: Bar,
name: 'bar'
};
console.log(b.tostring()); // doesn't work since the method doesn't exist
我假设Bar.prototype被本地对象的Javascript覆盖。我如何继承使用简写Bar.prototype = {}
并避免重复?
你为什么要修改的原型,而不是对象只是定义函数? – David
请仔细阐述,@David – Hawk
请参阅:http://google.github.io/styleguide/javascriptguide.xml?showone=Method_and_property_definitions#Method_and_property_definitions 为了调试和语言的安全性,最好不要触摸通常是一个物体的原型。 – David