所以我一直在阅读有关原型(prototype)的大量内容,并且我了解了大部分内容,我的意思是,我得到了以下内容。
var Animal = function(species) {
this.species = species;
};
Animal.prototype.getSpecies = function() {
return this.species;
}
var myDog = new Animal("Anderson");
alert(myDog.getSpecies());
我什至知道我可以创建一个新物种并将原型(prototype)设置为 Animal,然后能够调用 getSpecies()。是的!
令我困惑的是:
var Person = function(firstName, lastName) {
this.firstName= firstName;
this.lastName= lastName
};
var meToo = { fName: "ken", lName: "N" };
alert(meToo.constructor.prototype); // [object Object]
alert(Person.constructor.prototype); // function Empty(){}
http://jsfiddle.net/r0k3t/s8Sx7/9/
我试图找到一些东西来解释为什么 Person 的原型(prototype)是 function() {}?我认为它将被设置为全局对象“this”(在本例中是窗口)。另外 - 为什么我不能枚举它的属性?正在阅读this建议我可以使用 constructor.prototype 来检索我认为是“窗口”的对象,然后枚举属性。
很明显我错过了一些东西 - 谢谢!
最佳答案
Person
对象的原型(prototype)就是 Person.prototype
。不是 Person.constructor.prototype
,这是非常不同的:
Person.constructor
,是Function
函数,它构造所有函数。因为 Person
是一个函数,所以它的 .constructor
是 Function
。
Function
对象(所有函数)的原型(prototype)就是 Function.prototype
。所以,Person.constructor.prototype === Function.prototype
。
普通对象的构造函数是Object
函数。所有普通对象的原型(prototype)都是Object.prototype
,它是一个“[object Object]”
(优先选择console.dir
而不是警报
,查看更多)。
所谓普通对象,是指使用 {}
或 new Object()
创建的任何内容
关于javascript - 函数和对象的原型(prototype)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13916834/