javascript - 子类不能调用其父类的原型(prototype)方法

标签 javascript inheritance methods call prototype-programming

我正在学习 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/

相关文章:

javascript - 如何使用套接字将按钮的背景颜色数据发送到服务器

javascript - 如何在选择器级别和 react native 值中存储js对象?

c++ - 派生类不调用基类的成员函数

c++ - 公共(public)虚函数派生在 C++ 中的私有(private)

java - 对象初始化(Java)

javascript - Node.js/Javascript - 等到方法完成

javascript - 如何解决 ng-repeat AngularJS 中的 sort() 方法?

javascript - 检查倒计时是否结束

python父类 'wrapping'子类方法

javascript - 在JavaScript中的字符处拆分字符串