在 Javascript 中创建子类时,为什么要分配原型字段



Mozilla的Javascript文档说这是创建对象的好方法:

// 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 对象的原型方法与矩形对象一起使用。

var rect = new Rectangle();
rect.move(1, 1); // Outputs, 'Shape moved.'

当您跳过上述行时,这应该不起作用,因为您仍然创建矩形对象,并且您仍然有一个矩形原型,但您不使用 Shape 的原型作为矩形对象的基本原型,因此不应有可用的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.'

如果删除这些行,rect instanceof Shape将返回false

以下代码片段写入rect instanceof Shape这些行是否被注释掉。

// 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
// lines commented out:
//Rectangle.prototype = Object.create(Shape.prototype);
//Rectangle.prototype.constructor = Rectangle;
var rect = new Rectangle();
rect instanceof Rectangle; // true
document.getElementById("result").innerHTML = (rect instanceof Shape).toString();
<div id="result"></div>

最新更新