每个函数都有一个prototype
属性,它是在创建函数对象时分配的,它指向一个继承自的新创建的对象Object.prototype
,并且它有一个constructor
属性,它只是指向函数本身。
目的prototype
property 是提供一种使用构造函数来实现继承的方法。当您使用以下命令调用函数时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
另一种类似的情况是,当使用构造函数有两级或更多级别的继承时,最常见的方式是用来表示函数之间的继承关系,即分配prototype
第二层的属性,例如:
function Parent() {}
function Child () {}
Child.prototype = new Parent();
上面的代码有几个问题,首先,它执行了父构造函数的逻辑来创建继承关系,但那是另一个故事了,在上面的例子中constructor
属性也会受到影响,因为我们完全替换了Child.prototype
object:
var child = new Child();
child.constructor == Parent; // true
如果我们替换替换的值constructor
的财产Child.prototype
分配它后,它将显示预期的行为:
function Child() {}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child();
child.constructor == Child; // true