What does 'var that = this;' mean in JavaScript?

前端 未结 6 1015
后悔当初
后悔当初 2020-11-22 00:49

In a JavaScript file I saw:

function Somefunction(){
   var that = this; 
   ... 
}

What is the purpose of declaring that and

6条回答
  •  清歌不尽
    2020-11-22 01:17

    From Crockford

    By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

    JS Fiddle

    function usesThis(name) {
        this.myName = name;
    
        function returnMe() {
            return this;        //scope is lost because of the inner function
        }
    
        return {
            returnMe : returnMe
        }
    }
    
    function usesThat(name) {
        var that = this;
        this.myName = name;
    
        function returnMe() {
            return that;            //scope is baked in with 'that' to the "class"
        }
    
        return {
            returnMe : returnMe
        }
    }
    
    var usesthat = new usesThat('Dave');
    var usesthis = new usesThis('John');
    alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
          "UsesThis thinks it's called " + usesthis.returnMe().myName);
    

    This alerts...

    UsesThat thinks it's called Dave

    UsesThis thinks it's called undefined

提交回复
热议问题