This forum is now read-only. Please use our new forums at discuss.codecademy.com.

1292 points
554290d595e378f3e4000759_231708666
Submitted by
Michael Oles
over 5 years ago

Can someone explain how "This" works?

Maybe there is already another forum post on this but I don't understand how "This" works. I know that this is substituted with something else but how does the computer know what to substitute into the spot of "this?


1 vote

permalink

The computer knows what to put instead of "this" because the object you are using.
Im not an expert but here is an example:

Lets suppose that we have an object (myObj) that has a method (myMet):
This is the method

   myMet = function(){
    console.log("Hi my name is "+ this.name);  
    };

This is the Object

myObj.myMet();

In this case, the computer knows that "this" will be changed for "myObj" because the thing that is using the method, in this case "myObj". So, "this" will help you to use this method with other objects.
Example:

myObj2.myMet();

Here, "this" will be changed by "myObj2".

Sorry for my english problems :P I HOPE it helps :)

554 points
51d2704e8c1ccc0045006522_475040217
Submitted by
Kiven Cortes
over 5 years ago


1 vote

permalink

this is powerful and strange and confusing in JS.

var obj = {
    firstName: "Fred"
};
    // Test object
    var obj2 = {
    firstName: "James"
    };
obj.foo = function() {
    alert(this.firstName);
};
obj2.foo = function() {
    alert(this.firstName);
};
obj.foo();
obj2.foo();

this in line 9 is saying (what did you call last?)

  • In this instance, this refers to "Fred". Why? We called foo for the target object.
  • We told it to find this obj's firstName value.

This can be expanded greatly. But, the fact of the matter is that it demonstrates this quite well in a basic sense.

View here for more information:
http://stackoverflow.com/questions/4195970/what-does-this-mean

2126 points
512d3f8f7df8cbb462001736_165830919
Submitted by
Nicholas Hazel
over 5 years ago