1

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();

David G
  • 94,763
  • 41
  • 167
  • 253
user1427661
  • 11,158
  • 28
  • 90
  • 132
  • 1
    You can read about prototype and prototypal inheritance in [Stack Overflow](http://stackoverflow.com/questions/12201082/prototypal-inheritance-concept-in-javascript-as-a-prototype-based-language) [1]: http://stackoverflow.com/questions/12201082/prototypal-inheritance-concept-in-javascript-as-a-prototype-based-language – Dariush Jafari Sep 01 '12 at 17:56

4 Answers4

2
function Person() {
  this.identity = "fellow";
  this.logYou = function() {
    document.write('hi');
  };
};

When you call this.identity = "fellow"; the this keyword refers the context in which the function is running.
So if you call the function in the Global scope, this refers to window object:

Person();
alert(window.identity); // fellow

And if you instanciate the function, this keyword refers to the new object:

var Dude = new Person();
alert(Dude.identity); // fellow

So the function Person has no property identity.
If you want to have some property for your function:

Person.identity = "fellow";
alert(Person.identity); //  fellow
Dariush Jafari
  • 5,223
  • 7
  • 42
  • 71
1

logYou and logMe are methods stored on the prototype of Person so that inheriting objects may have that function to call. You can't call logYou on Person but what you can do is call it on its child, Dude:

Dude.logYou(); // hi
Dude.logMe(); // fellow
David G
  • 94,763
  • 41
  • 167
  • 253
1

These two lines

Person.logYou();   
Person.logMe(); 

throw an error an couse the code to stop executing because logYou and logMe do not exist as properties of Person.

Dude.logMe() and Dude.logYou() will work, printing fellow and hi, respectively.

Peter Olson
  • 139,199
  • 49
  • 202
  • 242
1

You cannot call

Person.logYou();  
Person.logMe();

as Person has no method logYou or logMe, when you remove these two lines, your code will start working

Dariush Jafari
  • 5,223
  • 7
  • 42
  • 71
Ankur
  • 12,676
  • 7
  • 37
  • 67