10

hi i am new with javascript

What is the benefit of using this line

var that = this

An example

function Person( firstname, lastname, age ) {

    this.firstname = firstname;

    this.lastname = lastname;

    this.age = age;

    getfullname = function() {

        return firstname + “ “ + lastname;
    };

    var that = this;


    this.sayHi = function() {

        document.write( “Hi my name is “ + getfullname() + “ and I am “ + that.age + “years old.”);

    };
}

thanks

Tarek Saied
  • 6,482
  • 20
  • 67
  • 111
  • 3
    Hi tarek11011, this is a question better suited for StackOverflow. In fact, the question is [already answered](http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript) a few times there – Dan McGrath Mar 17 '11 at 06:56
  • 2
    That question is about the use of var which isn't what is being asked here – jcoder Mar 17 '11 at 08:12
  • why does `getfullname` not have a `this` before it? – I Like Feb 15 '18 at 18:35

1 Answers1

15

because in the inner function this will not be the same object as in the outer, so by aliasing it to that you can make sure you are talking to the same object.

Zachary K
  • 3,205
  • 1
  • 29
  • 36