设置prototype.constructor的目的是什么 [英] What is the purpose of setting prototype.constructor
问题描述
我一直无法找到对此的明确解释.这是我在 MDN 上找到的一个简单示例.我唯一不明白的是为什么要设置构造函数.有人可以解释为什么需要这样做吗?是为了继承,以便引用正确的原型链吗?
I haven't been able to find a clear explanation of this. This is a straightforward example that I found on MDN. The only thing I don't understand is why the constructor is set. Can someone explain why this is needed? Is it for inheritance and so that the correct prototype chain is reffered to?
// 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.'
推荐答案
每当你创建一个函数,比如 function foo(){}
,JS 引擎也会创建一个匿名对象并将两者连接起来以类似的方式.
Whenever you create a function, say function foo(){}
, the JS engine also creates an anonymous object and connects the two in a similar fashion.
foo.prototype = {};
foo.prototype.constructor = foo;
属性名称constructor"和prototype"之所以如此,只是因为语义.标准名称可能是:
The property names "constructor" and "prototype" are so only because of semantics. It is possible that the standard names were:
foo.ping = {};
foo.ping.pong = foo;
<小时>
而设置prototype.constructor
"的目的很简单——能够使用那个类的构造函数.
And "the purpose of setting prototype.constructor
" is simple - to be able to use the constructor function of that class.
如果不需要调用构造函数,可以完全省略该属性.
If you don't need to call the constructor function, you can omit the property entirely.
要了解有关我推荐阅读的主题的更多信息http://www.javascripttutorial.net/javascript-prototype/和http://www.javascripttutorial.net/javascript-prototypal-inheritance/
To know more about the topic I recommend reading http://www.javascripttutorial.net/javascript-prototype/ and http://www.javascripttutorial.net/javascript-prototypal-inheritance/
这篇关于设置prototype.constructor的目的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!