开发者

in javascript whay use " var that = this "

开发者 https://www.devze.com 2023-02-17 03:56 出处:网络
hi i am new with javascript What is the benefit of using this line var that = this An example function Person( firstname, lastname, age ) {

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

精彩评论

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