JavaScript - 为什么设置原型原型不起作用
JavaScript - why doesn't setting prototypes prototype work?
我知道JavaScript中的继承可以通过以下内容(从MDN复制)来完成:
// Shape - superclass
function Shape() {
this.x = 0;
this.y = 0;
}
// superclass method
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info('Shape moved.');
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); // call super constructor.
}
// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
console.log('Is rect an instance of Rectangle? ' + (rect instanceof Rectangle)); // true
console.log('Is rect an instance of Shape? ' + (rect instanceof Shape)); // true
rect.move(1, 1); // Outputs, 'Shape moved.'
我不明白的是为什么要替换:
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
跟:
Rectangle.prototype.prototype = Shape.prototype;
不完成同样的事情吗?
在实例上执行类似的操作似乎工作正常。 例:
var rect = new Rectangle();
rect.__proto__.__proto__ = Shape.prototype;
但是不鼓励以这种方式操作原型
因为inst.__proto__ == Rectangle.prototype
.如果你想操作你的.prototype
对象的原型(即从它继承的内容),你需要使用
Rectangle.prototype.__proto__ = Shape.prototype;
相关文章:
- Magento Jquery引导程序和原型冲突?导航标签不起作用
- 对象原型在Canvas Game中不起作用
- JavaScript - 为什么设置原型原型不起作用
- Javascript:分配给对象或数组原型会导致括号不起作用
- 修改对象的原型不起作用
- 将js文件从原型迁移到jQuery不起作用
- 原型扩展jQuery在Internet Explorer中不起作用 - “不支持”
- 为什么原型JavaScript在这种情况下不起作用
- Javascript原型继承不起作用
- 通过原型扩展数学对象不起作用
- 原型函数在IE8中不起作用
- 在主干中向原型对象添加值不起作用
- 通过按钮点击调用原型函数不起作用
- 调用函数内部的原型方法不起作用
- javascript原型更改锚点颜色不起作用
- 为什么功能原型在这个小提琴里不起作用
- 多个元素原型不起作用
- 重写对象's构造函数's原型没有;不起作用
- 为什么对Array原型的更改在我的jQuery插件中不起作用
- 为什么我的实体模型框架的forEach原型不起作用