【问题标题】:Differences in inheritance of parent objects prototype [duplicate]父对象原型继承的差异[重复]
【发布时间】:2018-06-20 00:28:27
【问题描述】:

我找到了 3 种方法来继承另一个 Object-constructor 的原型:

我可以同时使用这三个吗? => 如果我在 Rectangle 实例上测试 draw() 方法,它们似乎可以工作......

还有其他方法吗?

function Shape(shapeName){
    this.shapeName = shapeName;
}
Shape.prototype.draw = function(){
    console.log('I am a '+this.shapeName+' and I am drawing myself');
}

function Rectangle(shapeName,l,b){
    Shape.apply(this,arguments);
    this.lengte = l;
    this.breadth = b;
}

// Possibility 1 ==> Rectangle.prototype = Object.create(Shape.prototype);
// Possibility 2 ==> Object.assign(Rectangle.prototype,Shape.prototype);
// Possibility 3 ==> Rectangle.prototype = Shape.prototype;

【问题讨论】:

  • 我不认为它们是完全等价的。当您创建Rectangle 的实例时,它们是否都为rectangle instanceof Shape 返回true?另外,您缺少 extends 关键字;)
  • ES6 类呢?
  • 只有第一个真正的继承

标签: javascript object inheritance constructor prototype


【解决方案1】:

我可以同时使用这三个吗?

有点,但我强烈建议使用可能性 1(加上将结果上的 constructor 设置为 Rectangle):

function Shape(shapeName){
    this.shapeName = shapeName;
}
Shape.prototype.draw = function(){
    console.log('I am a '+this.shapeName+' and I am drawing myself');
}

function Rectangle(shapeName,l,b){
    Shape.apply(this,arguments);
    this.lengte = l;
    this.breadth = b;
}

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

为什么我不使用可能性 2:它会复制所有内容,这意味着对 Shape.prototype 的后续修改不会被 Rectangle.prototype 继承。

为什么我不使用可能性 3:这意味着您不能提供 Shape 没有的 Rectangle 方法(因为添加到 Rectangle.prototype 是添加到 Shape.prototype,因为它们是相同的对象),如果您也以相同的方式创建了Triangle 并使用triangle = new Triangle() 创建triangle,它会错误地使triangle instanceof Rectangle 为真。


可能性 1 本质上也是 ES2015+ class 语法在您执行 class Rectangle extends Shape { } 时所做的。事实上,我会推荐使用什么(可能使用转译器):

class Shape {
    constructor(shapeName) {
        this.shapeName = shapeName;
    }
    draw() {
        console.log('I am a '+this.shapeName+' and I am drawing myself');
    }
}

class Rectangle extends Shape {
    constructor(shapeName, l, b){
        super(shapeName);
        this.lengte = l; // <=== Maybe you meant "length"?
        this.breadth = b;
    }
}

【讨论】:

  • @GiorgiMoniava:对于“可能性 3”而不是 2,这是正确的,但我认为这一点已经充分说明,让两个 prototype 属性引用同一个对象是没有用的。 :-)
猜你喜欢
  • 1970-01-01
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2022-07-27
  • 2019-01-24
  • 2016-07-04
  • 1970-01-01
  • 2020-12-28
相关资源
最近更新 更多