最佳答案
试图绕过 Javascript 的面向对象... ... 并且,像许多其他人一样,陷入了关于 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`.
In the above example, the object b
seems to have had the right constructor called (Bar
) – and it inherits the age property from Foo
. So why do many people suggest this as a necessary step:
Bar.prototype.constructor = Bar;
显然,正确的 Bar
构造函数 曾经是在构造 b
时调用,那么这个原型属性有什么影响呢?我很想知道“正确”设置构造函数属性实际上有什么不同ーー因为我看不出它对创建对象后实际调用哪个构造函数有任何影响。