【发布时间】:2015-08-20 10:18:20
【问题描述】:
想象以下 JavaScript 示例场景:
- 我们为可以出现在平面上的事物建模(例如形状或点)
- 其中一些东西(如圆圈)可以有标签
鉴于以下代码实现(Circle 继承自 Shape 和 Labelable)如何使用 instanceof 运算符让每个圆同时成为 Shape 和 Labelable 的实例?。请注意,与方法相关的代码在此示例中不相关,但应该被继承。
功能形状(面积){
this.area = 面积;
}
Shape.prototype.sayArea = function(){
alert('My area is ' + this.area);
};
function Circle(area, center, label){
Shape.call(this, area);
Labelable.call(this, label);
this.center = center;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.sayCenter = function(){
alert('My center is ' + this.center);
};
function Labelable(label){
this.label = label;
}
Labelable.prototype.sayLabel = function(){
alert('My label is ' + this.label);
};
Circle.prototype.sayLabel = Labelable.prototype.sayLabel;
var c = new Circle(100, [0, 0], 'myLabel');
c instanceof Circle; // True
c instanceof Shape; // True
c instanceof Labelable; // False although we have used .call() and prototype is also inherited , how to make it true?
【问题讨论】:
-
你不能因为原型链不知道
Labelable -
原型链是单个列表。做到这一点的唯一方法是让一个超类成为另一个的子类。
-
@ArunPJohny 或 Pointy 如果您愿意,请提供解释为什么它不可能的答案,以便我可以将其标记为已接受。尖锐的解决方法无效,因为并非所有形状都是可标注的,而且不仅形状可以有标签。
-
@Pointy 或 ArunPJohny 请记住,您仍然可以发布一个答案,解释为什么这是不可能的,所以我可以接受。目前有一个答案,但不谈论问题(instanceof 运算符),而是谈论原型链。
标签: javascript inheritance instanceof duck-typing