Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  132] [ 2]  / answers: 1 / hits: 21028  / 10 Years ago, tue, july 8, 2014, 12:00:00

I am trying to understand better the use of that and this in JavaScript. I am following Douglas Crockford's tutorial here: http://javascript.crockford.com/private.html
but I am confused regarding a couple of things. I have given an example below, and I would like to know if I am making a correct use of them:



function ObjectC()
{
//...
}

function ObjectA(givenB)
{
ObjectC.call(this); //is the use of this correct here or do we need that?

var aa = givenB;
var that = this;

function myA ()
{
that.getA(); //is the use of that correct or do we need this?
}

this.getA = function() //is the use of this correct?
{
console.log(ObjectA);
};


}

function ObjectB()
{

var that = this;

var bb = new ObjectA(that); //is the use of that correct or do we need this?

this.getB = function()
{
return bb;
};

that.getB(); //is the use of that correct or do we need this?


}


Note this is just an example.


More From » this

 Answers
50

ObjectC.call(this); //is the use of this correct here or do we need that?



The first thing you need to understand is how the this keyword works. It's value depends on how the function/method/constructor is called.



In this case, function ObjectA is a constructor, so you can just use this inside the code of it. In fact, with var that = this; you declare them to be absolutely identical (unless you use that before assigning to it).




function myA() {
that.getA(); //is the use of that correct or do we need this?
}



Again, it depends on how the function is called - which you unfortunately have not show us. If if was a method of the instance, this would have been fine; but but it seems you will need to use that.




this.getA = function() //is the use of this correct?



As stated above, using that would not make any difference.




var bb = new ObjectA(that) //is the use of that correct or do we need this?
var that = this;



that is undefined when it is used here. And it would be supposed to have the same value as this anyway. Better use this.




that.getB(); //is the use of that correct or do we need this?



Again, both have the same effect. But since you don't need that, you should just use this.


[#70275] Sunday, July 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
allans

Total Points: 336
Total Questions: 120
Total Answers: 119

Location: Peru
Member since Mon, Jun 6, 2022
2 Years ago
;