在构造函数的内部和外部添加原型方法 [英] Adding prototype methods outside vs inside of constructor function
问题描述
我正在学习JavaScript原型,想问你以下代码是否正确:
I was learning prototype in JavaScript and wanted to ask you if the following code is correct:
function Shape() {
Shape.prototype.duplicate = function() {
console.log('Duplicate');
}
}
function Circle() {
Circle.prototype = Object.create(Shape.prototype);
}
或者我应该使用以下代码:
Or should I use this code:
function Shape() {
}
Shape.prototype.duplicate = function() {
console.log('Duplicate');
}
function Circle() {
}
Circle.prototype = Object.create(Shape.prototype);
推荐答案
tl; dr:应该在构造函数的外部 初始化原型.
tl;dr: The prototype should be initialized outside the constructor.
prototype对象应该只在一次中初始化/创建.在构造函数中对其进行更改意味着每次创建新实例时,都会以一种或另一种方式更改原型.
The prototype object is something that should be initialized/created only once. Changing it inside the constructor means that every time a new instance is created, the prototype is changed one way or the other.
这种方式破坏了原型的目的,因为它们应该是原型,并且应该在所有实例之间共享(以保存"内存).
That kind of defeats the purpose of prototypes because they should be setup ones and shared across all instances (to "save" memory).
对于 Shape
来说不是很明显,但是对于 Circle
来说却更明显:
It's not so evident for Shape
, but it becomes more evident for Circle
:
function Shape() {
Shape.prototype.duplicate = function() {
console.log('Duplicate');
}
}
function Circle() {
Circle.prototype = Object.create(Shape.prototype);
}
var c1 = new Circle();
var c2 = new Circle();
console.log(
Object.getPrototypeOf(c1) === Object.getPrototypeOf(c2),
':-O every Circle instance has its own prototype'
);
c1.duplicate();
// can't even call `c1.duplicate` because
// `Circle.prototype = Object.create(Shape.prototype);` happens
// *after* the first instance was created
这篇关于在构造函数的内部和外部添加原型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!