简体   繁体   中英

what's the purpose to use that in the javascript function?

I saw a style that use

var test = function() {
    var that = this;
    this.show() {
        that.***;
    }
}

I am wondering why use that in the function?

The purpose of using that is to capture this in the context in which the function was constructed. When the function is called, this is in a different context (The caller I believe) so that when test() is called, this would not be what you expected it to be (unless you understand JavaScript, in which case it would be what you expect it to be, but not what you want it to be).

To capture the correct value of this . JS's this semantics are a bit... funky, IMO.

What's "correct" depends on what you actually need, but this is evaluated late. In other words, this 's value during runtime may well be different than its value at function definition time. By capturing it at definition time you can ensure it's what you need it to be.

Because the this keyword is not persistent between functions in javascript. If you save it in a local variable using that = this it can be accessed from within the local functions regardless what context you apply to them.

var test = function() {
    console.log(this); // foo
    var that = this;
    var inner = function() {
        console.log(this); // bar
        console.log(that); // foo
    }
    inner.call('bar');
};

test.call('foo');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM