3

function test1() {
  this.name = 'test1';
  var that = this;

  function test2() {
    this.name = 'test2';
    console.log(that.name);
  }

  test2();
}

test1();

When this executes, I expect the console to log out test1. Why do I get test2 instead? I expect the that variable to hold a reference to the test1 function.

Andrew Marshall
  • 89,426
  • 20
  • 208
  • 208
Krimson
  • 6,306
  • 9
  • 47
  • 86
  • 4
    Because `that` and both `this`es point to the global object `window`. You're not creating an instance (using `new`) so that the `this` (of `test1`) will be that instance, you are just calling the functions directly. – ibrahim mahrir May 27 '18 at 02:03
  • 1
    Try: `var a = new test1();` Or just `new test1();` (for short). – ibrahim mahrir May 27 '18 at 02:05
  • It would help you undersant if you logged those vriables. – ibrahim mahrir May 27 '18 at 02:09
  • Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Isaac May 27 '18 at 02:32
  • *"that variable to hold a reference to the test1 function."* That isn't what "this" or "that" are in JavaScript. They don't hold references to functions, they hold object references. – meager May 27 '18 at 03:46

2 Answers2

1

Your variable that becomes an object reference since you assign keyword this to it. That means the variable that will be an object and it will have a reference to this(that is, the current object).

Further, the variable that is not a value type. It is an object.

For more on this, search on " value type vs reference types ".

Hope this helps.

Chiran K.
  • 406
  • 2
  • 14
0

In a function definition, this refers to the "owner" of the function. Please find the description in inline comments. Rearranging your code according to the order of execution,

test1();                      //Now this is called by window object
function test1() {
  this.name = 'test1';        //window.name = 'test1';
  var that = this;            //that is also now window obj
  test2();                    //this.test2 or window.test2()
  function test2() {
    this.name = 'test2';      //window.name is now test 2
    console.log(that.name);   //since in third step, that is window, that.name or window.name is now test 2
  }
}
Rohith Murali
  • 4,864
  • 2
  • 18
  • 23