in javascript why use " var that = this " [duplicate]
hi i am new with javascript
What is the b开发者_开发问答enefit 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
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.
精彩评论