让instanceof操作符在JavaScript中与多个超类一起工作

Getting instanceof operator to work with multiple super classes in JavaScript

本文关键字:超类 一起 工作 instanceof 操作符 JavaScript      更新时间:2023-09-26

想象一下下面的JavaScript示例场景:

  1. 我们对可以出现在平面上的事物(如形状或点)进行建模
  2. 有些东西(比如圆圈)可以有一个标签

给定以下代码实现(圆圈从形状和标签继承)我怎么能让每个圆圈都是使用instanceof操作符的形状和标签的实例?。请注意,与方法相关的代码在本例中是不相关的,但它应该被继承。函数形状(地区){这一点。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?

您可以尝试使用具有extend功能的库向对象添加多个原型。