【问题标题】:Getting instanceof operator to work with multiple super classes in JavaScript让 instanceof 运算符与 JavaScript 中的多个超类一起工作
【发布时间】:2015-08-20 10:18:20
【问题描述】:

想象以下 JavaScript 示例场景:

  1. 我们为可以出现在平面上的事物建模(例如形状或点)
  2. 其中一些东西(如圆圈)可以有标签

鉴于以下代码实现(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


【解决方案1】:

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

【讨论】:

  • 据我所知原型将被继承,但它不会解决与insntanceof运算符相关的问题。其他人评论说无法解决。
  • object.getPrototypeOf 怎么样? Object 有自己的一套工具,可以作为替代工具。
  • 这将有助于解决instanceof 运算符的问题吗?如果是这样,怎么做?否则您可以解释为什么无法解决instanceof 运算符问题,我会接受您的回答。
猜你喜欢
  • 2018-06-08
  • 2020-02-13
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 2020-12-07
相关资源
最近更新 更多