JavaScript - 为什么设置原型(prototype)原型(prototype)不起作用?

标签 javascript

据我所知,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;

但是以这种方式操作原型(prototype)是 discouraged

最佳答案

因为inst.__proto__ == Rectangle.prototype。如果您想操作 .prototype 对象的原型(prototype)(即它继承的内容),则需要使用

Rectangle.prototype.__proto__ = Shape.prototype;

关于JavaScript - 为什么设置原型(prototype)原型(prototype)不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28239422/

相关文章:

javascript - Building Typescript : [! ] Error: Unexpected token (注意你需要插件来导入不是 JavaScript 的文件)

javascript - JQuery 选择器选择 GridView 分页

javascript - 如何使用javascript在localstorage中存储带有文本和图像的li

javascript .replace 一个 html 标签不替换

javascript - 如何在正确的上下文中引用 Knockout.js 对象和对象数组

javascript - 为什么 Rails 的 Assets 缓存在暂存环境中不适用于 JS?

javascript - NodeJS 中的客户端/服务器操作检测

javascript - 找不到 "application"模板或 View 。什么都不会呈现对象 {fullName : "template:application"}

javascript - 如何分析 ArangoDB Foxx 应用程序中的内存使用情况

javascript - Angular 'reject' 是 Angular Controller 中未定义的错误