Mozilla's Javascript docs说这是创建对象的好方法:
// 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();
rect instanceof Rectangle; // true
rect instanceof Shape; // true
rect.move(1, 1); // Outputs, 'Shape moved.'
但是,在练习的时候,我故意跳过了这行
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
所有的行为似乎都完全正常。似乎跳过这些行没有任何后果。比如我还是创建了Rectangle
对象,调用它的属性等等。
这些行是多余的吗?我错过了什么?
最佳答案
Rectangle.prototype = Object.create(Shape.prototype);
这一行使您能够将 Shape 对象的原型(prototype)方法与您的 Rectangle 对象一起使用。
var rect = new Rectangle();
rect.move(1, 1); // Outputs, 'Shape moved.'
当你跳过上面提到的那行时这应该不起作用,因为你仍然创建 Rectangle 对象,你仍然有一个 Rectangle 原型(prototype),但是你没有使用 Shape 的原型(prototype)作为你的 Rectangle 对象的基本原型(prototype)和结果没有 Shape.prototype.move
应该可用。
rect instanceof Shape; // true
此外,正如 ProgramFOX 所说,如果您删除上面的行,此行将不会导致 true
。
这是包含上述更改的代码段:
// 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.log('Shape moved.');
};
// Rectangle - subclass
function Rectangle() {
Shape.call(this); // call super constructor.
}
Rectangle.prototype.doSomething = function() {
console.log('Rectangle alert.');
}
// subclass extends superclass
//Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
console.log(rect instanceof Shape); // Does NOT output true
rect.doSomething(); // DOES output 'Rectangle alert.'
rect.move(1, 1); // Does NOT output 'Shape moved.'
关于javascript - 在 Javascript 中创建子类时,为什么要分配原型(prototype)字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26575648/