在javascript中为什么使用“var that = this”

时间:2011-03-17 06:39:45

标签: javascript

嗨,我是javascript的新手

使用此行有什么好处

var that = this

一个例子

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.”);

    };
}

感谢

1 个答案:

答案 0 :(得分:15)

因为在内部函数中,与外部函数不是同一个对象,所以通过将它别名为那个,你可以确保你正在与它相同对象

相关问题