试图绕过Javascript对OO的看法......和许多其他人一样,对constructor财产产生混淆.特别是constructor财产的重要性,因为我似乎无法使其产生任何影响.例如:
function Foo(age) {
this.age = age;
}
function Bar() {
Foo.call(this, 42);
this.name = "baz";
}
Bar.prototype = Object.create(Foo.prototype);
var b = new Bar;
alert(b.constructor); // "Foo". That's OK because we inherit `Foo`'s prototype.
alert(b.name); // "baz". Shows that Bar() was called as constructor.
alert(b.age); // "42", inherited from `Foo`.
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,对象b似乎有正确的构造函数call(Bar) - 并且它继承了age属性Foo.那么为什么许多人认为这是必要的步骤:
Bar.prototype.constructor = Bar;
Run Code Online (Sandbox Code Playgroud)
显然,Bar构造时会调用正确的构造函数b,因此这个原型属性有什么影响?我很想知道它实际上使构造函数属性设置'正确'有什么实际区别 - 因为我无法看到它对创建对象后实际调用的构造函数有任何影响.
在JavaScript中,每个函数的原型对象都有一个不可枚举的属性constructor,该属性指向函数(EcmaScript§13.2).它不用于任何本机功能(例如instanceof只检查原型链),但是我们鼓励在覆盖prototype函数的属性以进行继承时调整它:
SubClass.prototype = Object.create(SuperClass.prototype, {
constructor: {value:SubClass, writable:true, configurable:true}
});
Run Code Online (Sandbox Code Playgroud)
但是,我们(包括我)是否只是为了清晰和整洁而这样做?是否存在依赖于该constructor属性的真实用例?