javascript - 在 Javascript 中创建子类时,为什么要分配原型(prototype)字段?

标签 javascript object prototype

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/

相关文章:

javascript - 在 javascript 中使用正则表达式匹配并返回 [] 中包含的所有字符串

javascript - 从年龄获取出生日期的逻辑以年月日表示

javascript - 按索引位置解析json对象数组

perl - 在 Perl 中使用原型(prototype)在子例程 args 上声明数组引用上下文是一件好事吗?

javascript - for-in JavaScript 语句中的 IE8 错误?

javascript - 使用 ng-messages 验证动态表单

javascript - $routeProvider - 根据 URL 注入(inject) Controller 依赖

javascript - 读取Javascript对象

c++ - 初级 C++ : object creation at runtime without knowing how many objects to create

javascript - JS 继承和变异原型(prototype)