in javascript whay use " var that = this "
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.a开发者_如何学Pythonge = 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
this
is context sensitive. Using that
makes sure that when sayHi
is called it can use the this
value from when getfullname
was called.
Usually it's to fix the meaning of this to what it refers to at the time that is assigned. it wouldn't make any difference in your example, but it can do when a function is called from a different context.
In Javascript this is a rather fluid concept. It is not the same as this in OO languages like c#.
精彩评论