Kenn
Kenn

Reputation: 2769

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(). 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/

I was trying to find something that explains why the prototype for Person is function() {}? I thought it would be set to the global object, 'this' (which in this case is window). 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.

So clearly I am missing something - thanks!

Upvotes: 0

Views: 86

Answers (1)

Esailija
Esailija

Reputation: 140230

The prototype for Person objects, is just Person.prototype. Not Person.constructor.prototype, which is very different:

Person.constructor, is the Function function, which constructs all functions. Because Person is a function, its .constructor is Function.

The prototype of Function objects (all functions), is just Function.prototype. So, Person.constructor.prototype === Function.prototype.

The constructor of plain objects is the Object function. The prototype of all plain objects is Object.prototype, which is an "[object Object]" (Prefer console.dir over alert, to see more).

By plain object, I mean anything created with {} or new Object()

Upvotes: 3

Related Questions