我在阅读 JavaScript Garden http://bonsaiden.github.com/JavaScript-Garden/ 时了解到了 JavaScript 中的原型,其中有一个示例如下:
请注意阅读这行代码:确保将 Bar 作为实际构造函数列出。我真的不知道这是做什么/是什么。我尝试过使用和不使用最后一行来创建 Bar() 的新实例。但是在这些实例上调用"value"或"method"返回完全相同的结果。所以我想知道,指定构造函数的必要性是什么(我认为肯定有一个)。谢谢!
function Foo() {
this.value = 42;
}
Foo.prototype = {
method: function() {}
};
function Bar() {}
// Set Bar's prototype to a new instance of Foo
Bar.prototype = new Foo();
Bar.prototype.foo = 'Hello World';
// Make sure to list Bar as the actual constructor <-------------------
Bar.prototype.constructor = Bar;
请注意阅读这行代码:确保将 Bar 作为实际构造函数列出。我真的不知道这是做什么/是什么。我尝试过使用和不使用最后一行来创建 Bar() 的新实例。但是在这些实例上调用"value"或"method"返回完全相同的结果。所以我想知道,指定构造函数的必要性是什么(我认为肯定有一个)。谢谢!
Object.prototype.constructor.prototype.constructor.prototype.constructor == Object;
;-) - Christian C. Salvadó