Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in javascript why use " var that = this " [duplicate]

Tags:

javascript

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

like image 830
Tarek Saied Avatar asked Mar 17 '11 06:03

Tarek Saied


1 Answers

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.

like image 181
Zachary K Avatar answered Oct 17 '22 08:10

Zachary K