简体   繁体   English

函数和对象的原型构造函数

[英]Prototype constructor for functions and objects

So I have been doing a lot of reading about the prototype and I get it for the most part, I mean, I get the following. 因此,我一直在大量阅读有关原型的内容,并且我得到了大部分,我的意思是,我得到了以下内容。

var Animal = function(species) {
    this.species = species;
};
Animal.prototype.getSpecies = function() {
    return this.species;
}
var myDog = new Animal("Anderson");    
alert(myDog.getSpecies());

I even understand that I could create a new species and set the prototype to Animal and then be able to call getSpecies(). 我什至知道我可以创建一个新物种并将原型设置为Animal,然后能够调用getSpecies()。 Yeah! 是的

What confuses me is this: 让我感到困惑的是:

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/ http://jsfiddle.net/r0k3t/s8Sx7/9/

I was trying to find something that explains why the prototype for Person is function() {}? 我试图找到可以解释为何Person的原型是function(){}的东西? I thought it would be set to the global object, 'this' (which in this case is window). 我认为它将被设置为全局对象“ this”(在本例中为窗口)。 Also - why can't I enumerate the properties of it? 另外-为什么我不能列举它的属性? Reading this would suggest that I could use constructor.prototype to retrieve the object which I thought would be 'window' and then just enumerate the properties. 阅读将表明我可以使用Constructor.prototype检索我认为是“窗口”的对象,然后只枚举属性。

So clearly I am missing something - thanks! 很明显,我缺少一些东西-谢谢!

The prototype for Person objects, is just Person.prototype . Person对象的原型就是Person.prototype Not Person.constructor.prototype , which is very different: 不是Person.constructor.prototype ,这是非常不同的:

Person.constructor , is the Function function, which constructs all functions. Person.constructorFunction函数,它构造所有函数。 Because Person is a function, its .constructor is Function . 因为Person是一个函数,所以它的.constructorFunction

The prototype of Function objects (all functions), is just Function.prototype . Function对象(所有函数)的原型就是Function.prototype So, Person.constructor.prototype === Function.prototype . 因此, Person.constructor.prototype === Function.prototype

The constructor of plain objects is the Object function. 普通对象的构造函数是Object函数。 The prototype of all plain objects is Object.prototype , which is an "[object Object]" (Prefer console.dir over alert , to see more). 所有普通对象的原型都是Object.prototype ,它是一个"[object Object]" (将console.dir Object.prototypealert ,以查看更多信息)。

By plain object, I mean anything created with {} or new Object() 普通对象是指用{}new Object()创建的任何new Object()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM