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!
The prototype for
Personobjects, is justPerson.prototype. NotPerson.constructor.prototype, which is very different:Person.constructor, is theFunctionfunction, which constructs all functions. BecausePersonis a function, its.constructorisFunction.The prototype of
Functionobjects (all functions), is justFunction.prototype. So,Person.constructor.prototype === Function.prototype.The constructor of plain objects is the
Objectfunction. The prototype of all plain objects isObject.prototype, which is an"[object Object]"(Preferconsole.diroveralert, to see more).By plain object, I mean anything created with
{}ornew Object()