JavaScript: that vs this

javascript, this

Solution

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`.

Problem

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.

Original source