我正在学习JS原型。子类不能调用其父类的原型方法
从Java
语言点我期望,SpecificRectangle
对象将有权访问area()
方法,由于area()是其父类(Rectangle类)原型的方法。
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()
什么解释,这种封装的原因是什么?
不错,工作正常 – sergionni 2011-12-28 13:28:29
你不应该使用'SpecificRectangle.prototype = new Rectangle()'。它工作很多次,但原则上是不正确的。如果你有ES5,你应该使用'SpecificRectangle.prototype = Object.create(Rectangle.prototype)'来代替,如果你不能保证ES5,你应该像'function create(proto){function f(){} f一样定义create。原型=原型;返回新的f(); }'并发出'SpecificRectangle.prototype = create(Rectangle.prototype)'。问题是,原型不应该是超类的初始实例,它应该只是从原型继承而不实际初始化。 – 2011-12-28 14:16:51
感谢您的评论。这导致我阅读这篇关于你所描述的问题的文章(http://www.bennadel.com/blog/2180-Your-Javascript-Constructor-Logic-May-Break-Prototypal-Inheritance.htm) [第](HTTP://www.bennadel。com/blog/2184-Object-create-Improves-Based-Inheritance-In-Javascript-It-Doesn-t-Replace-It.htm)在Object.create(阅读注释)。 – 2011-12-28 14:34:55