I am trying to understand the key word this
in JavaScript, it's a bit confusing.
I saw two ways of using this, which I am not entirely sure to understand. But, here is what I understood, correct me if it is wrong.
First way to use
this
:var setAge = function (newAge) { this.age = newAge; }; // now we make bob var bob = new Object(); bob.age = 30; // and down here we just use the method we already made bob.setAge = setAge; // change bob's age to 50 here bob.setAge(50);
What I get from this one that
this
is being used as global, like you can change the age to whatever you want.Second way to use
this
:var square = new Object(); square.sideLength = 6; square.calcPerimeter = function() { return this.sideLength * 4; }; // help us define an area method here square.calcArea = function() { return this.sideLength * this.sideLength }; var p = square.calcPerimeter(); var a = square.calcArea();
I am not sure about this one, please explain to me... as my brain is trying to make sense of
this
...