【问题标题】:What is the purpose of setting prototype.constructor [duplicate]设置prototype.constructor的目的是什么[重复]
【发布时间】:2016-01-02 21:33:44
【问题描述】:

我无法找到对此的明确解释。这是我在 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.'

【问题讨论】:

标签: javascript prototype


【解决方案1】:

每当您创建一个函数时,比如function foo(){},JS 引擎也会创建一个匿名对象并以类似的方式连接两者。

foo.prototype = {};
foo.prototype.constructor = foo;

属性名称“构造函数”和“原型”只是因为语义。标准名称可能是:

foo.ping = {};
foo.ping.pong = foo;

而“设置prototype.constructor的目的”很简单——能够使用该类的构造函数

如果不需要调用构造函数,可以完全省略该属性。

要了解我推荐阅读的主题的更多信息 http://www.javascripttutorial.net/javascript-prototype/http://www.javascripttutorial.net/javascript-prototypal-inheritance/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-26
    • 2015-10-03
    • 2012-08-12
    • 2015-08-07
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多