开发者

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

This question already has answers here: What does 'var that = this;' mean in JavaScript? (6 answers) Closed 8 years ago.

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜