【发布时间】: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