我正在学习 JS 原型(prototype)。
从 Java
语言的 Angular 来看,我希望 SpecificRectangle
对象可以访问 area()
方法,因为 area() 是其父类(Rectangle 类)原型(prototype)的方法。
function Rectangle(w,h){
this.width = w;
this.height=h;
}
Rectangle.prototype.area = function(){return this.width*this.height}
function SpecificRectangle(w,h,angle){
Rectangle.call(this,w,h);
SpecificRectangle.prototype=new Rectangle();
}
var specrec = new SpecificRectangle(7,8,45);
我根本无法在 SpecificRectangle
实例上调用 area()
方法。
标准 JS 错误:
TypeError: specrec.area is not a function
[Break On This Error] specrec.area()
这样封装的解释和原因是什么?
最佳答案
老实说,我不知道确切的原因,但你需要在构造函数之外设置原型(prototype):
function SpecificRectangle(w, h, angle) {
Rectangle.call(this,w,h);
}
SpecificRectangle.prototype = new Rectangle();
SpecificRectangle.prototype.constructor = SpecificRectangle; // Otherwise instances of SpecificRectangle would have a constructor of Rectangle
工作示例 here .
编辑@herby 的评论:
根据父类(super class)构造函数的构建方式,upper 方法似乎确实可以破坏原型(prototype)继承(参见 this article)。
一个更强大的解决方案是使用 Object.create
(source - 感谢 herby)
// in case Object.create does not exist
if (typeof Object.create !== 'function') {
Object.create = function(o) {
var F = function() {};
F.prototype = o;
return new F();
};
}
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return this.width * this.height
}
function SpecificRectangle(w, h, angle) {
Rectangle.call(this, w, h);
}
SpecificRectangle.prototype = Object.create(Rectangle.prototype);
SpecificRectangle.prototype.constructor = SpecificRectangle;
var r = new SpecificRectangle(100, 50, 30);
alert(r.area());
关于 jsfiddle 的更新示例
关于javascript - 子类不能调用其父类的原型(prototype)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8656131/