让instanceof操作符在JavaScript中与多个超类一起工作
Getting instanceof operator to work with multiple super classes in JavaScript
想象一下下面的JavaScript示例场景:
- 我们对可以出现在平面上的事物(如形状或点)进行建模
- 有些东西(比如圆圈)可以有一个标签
给定以下代码实现(圆圈从形状和标签继承)我怎么能让每个圆圈都是使用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
功能的库向对象添加多个原型。
相关文章:
- Javascript”;onmousemove”;事件无法与类一起使用
- 理解es6-mixin超类约定
- 可以“;超级“;可以在子类的方法内部使用,在不直接引用的情况下调用相应的超类方法
- 调用子类函数时调用的超类函数
- 与超类的依赖关系
- jQuery.not()选择器无法与类一起工作
- 如何在javascript中从超类扩充方法
- javascript对象继承-子类和超类
- 调用Class.prototype=new MyClass()是否确保每次都重新实例化超类
- BackboneJS-可能回调多级继承的超类
- Javascript继承:从超类的方法设置子类的属性
- 是否可以将 .val 与类一起使用
- 使用 Javascript 创建一个超类(继承)
- JavaScript 原型超类
- 如何将相同的切换注释与两个不同的 ID/类一起使用
- 在主干中调用超类方法
- Javascript继承,可以访问“超类”中的*所有*方法
- 如何使用 sinon 存根/模拟从“超类”复制的依赖项方法
- 有没有一种方法可以根据Coffeescription中的超类值在原型上定义对象
- 让instanceof操作符在JavaScript中与多个超类一起工作