Can someone clear up what I’m doing wrong with my code? I’m a total newb, simply trying to experiment with how to create objects, prototypes, and what the this command refers to in the context of prototypes. However, none of my code is working on jFiddle. I know this code is completely nonsensical, but I’m just trying to find out what the document prints in various cases to get a more concrete grasp of how objects, prototypes, constructors, and the “this” keyword works. But NOTHING is showing up at all!
function Person(identity) {
this.identity = "fellow";
this.logYou = function() {
document.write('hi');
};
};
Person.prototype.logMe = function() {
document.write(this.identity);
};
var Dude = new Person("stud");
Person.logYou();
Person.logMe();
Dude.logMe();
When you call
this.identity = "fellow";thethiskeyword refers the context in which the function is running.So if you call the function in the Global scope,
thisrefers towindowobject:And if you instanciate the function,
thiskeyword refers to the new object:So the function
Personhas no propertyidentity.If you want to have some property for your function: