开发者

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#.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜