Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `this` refer to?

Tags:

javascript

I have a JavaScript class:

function Person(n){
  // ...
}

Outside of the class, I have the following code:

Person.prototype.shower = function(){ this.dirtFactor=2 }

What does this in the above code refer to? Does it refer to prototype, or to the Person class?

like image 430
Mellon Avatar asked Mar 01 '11 10:03

Mellon


2 Answers

The meaning of this depends on how you call the function, not how you define it.

Assuming you do something like:

var bob = new Person('whatever n is');
bob.shower();

Then this will be bob (which will be an instance of Person).

like image 113
Quentin Avatar answered Oct 13 '22 13:10

Quentin


Okay, basics first: when you write function Person(o) { ... }, you are not declaring a class -- JavaScript does not class based, but object based. This statement simply declares a function (which incidentally, are objects as well).

Next, when you create an object like this:

var mellon = new Person('Mellon');

you are creating an object, whose constructor (of sorts) is Person.

Now, read this carefully: since mellon's constructor is Person, all methods in Person's prototype will be available in the object.

So if you write:

Person.prototype.shower = function(){ this.dirtFactor=2 }  

then the method mellon.shower() will be available.

I recommend going through Mozilla's intro to OOP in Javascript for some details on this topic.


So to answer your question: this refers to the object with which the method shower was invoked. In the above case, it would be mellon.

like image 33
jrharshath Avatar answered Oct 13 '22 12:10

jrharshath