每个函数都有一个prototype
属性,创建函数对象时,它的分配,它指向一个新创建的对象,从Object.prototype
继承,它有一个constructor
属性,简单地回指向函数本身。
prototype
属性的目的是给出一种方法来实现继承,使用构造函数。当您使用new
运算符调用函数时,它将创建一个从该构造函数的prototype
继承的新对象。现在
,该constructor
财产的目的是有办法重新引用已创建的对象的构造函数,例如:
function Foo() {}
// default value of the property:
Foo.prototype.constructor == Foo; // true
此属性是由的Foo
“实例”继承,这样你就可以知道哪个构造函数用于创建一个对象:如果您分配一个新的对象给函数的原型
var foo = new Foo();
foo.constructor == Foo;
,这种关系将丢失:
function Bar() {}
Bar.prototype = { inherited: 1 };
Bar.prototype.constructor == Bar; // false
Bar.prototype.constructor == Object; // true
而且这也影响了功能的实例:
var bar = new Bar();
bar.constructor == Bar; // false
bar.constructor == Object; // true
另一个类似的例子是,当你有使用构造继承的两个或两个以上的水平,最常见的方式是用来表示继承关系在功能之间,是指定第二级的属性,例如:
function Parent() {}
function Child() {}
Child.prototype = new Parent();
上面的代码有几个问题,第一,它执行父构造函数来创建的继承关系的逻辑,但那是另一个故事,在上面的例子中constructor
财产也受到影响,因为我们更换完全Child.prototype
对象:
var child = new Child();
child.constructor == Parent; // true
如果我们更换分配给它更换后的Child.prototype
的constructor
属性的值,它会显示预期的行为:
function Child() {}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child();
child.constructor == Child; // true
来源
2011-10-10 22:00:11
CMS
感谢您的详细解释。这一切都有道理。唯一让我感到困惑的东西,但我可以忽略的是它看起来有点儿在Child.prototype.constructor = Child –
@Nik,不客气!是的,这确实是循环设计,例如:'Object.prototype.constructor.prototype.constructor.prototype.constructor == Object;';-) – CMS