我想做的是继承 id
和name
来自TField
并覆盖 render
TField
的功能。我想知道这是否是在 JavaScript 中实现继承的标准方法。
var TField=function(jData)
{
this.id=jData.id;
this.name=jData.name;
this.attributes=jData.attributes;
this.render=function(){
alert('TField render.');
};
};
var TChildField=function(jData)
{
var t= new TField(jData);
t.render=function(){
alert('TChildField render.');
}
return t;
}
var tobj={id:"1",name:"test",attribute:{}};
var c= new TChildField(tobj);
alert(c.id);
alert(c.name);
最佳答案
首先,从构造函数中删除 render
定义并将其直接添加到原型(prototype)中可能是一个好主意:
TField.prototype.render=function(){
alert('TField render.');
};
其次,要设置构造函数的继承,请使用:
var TChildField=function(jData)
{
TField.call(this,jData)
}
然后,链接两个原型(prototype)
TChildField.prototype=Object.create(TField.prototype)
最后,覆盖 TChildField
的 render()
TChildField.prototype.render=function(){
alert('TChildField render.');
};
var TField=function(jData)
{
this.id=jData.id;
this.name=jData.name;
this.attributes=jData.attributes;
};
TField.prototype.render=function(){
alert('TField render.');
};
var TChildField=function(jData)
{
TField.call(this,jData)
}
var tobj={id:"1",name:"test",attribute:{}};
TChildField.prototype=Object.create(TField.prototype)
TChildField.prototype.render=function(){
alert('TChildField render.');
};
var c= new TChildField(tobj);
alert(c.id);
alert(c.name);
关于javascript - javascript中的经典继承实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15874375/