Confusion with “this” object in JavaScript anonymous functions

前端 未结 3 1171
失恋的感觉
失恋的感觉 2020-12-10 22:08

Hi I have following JavaScript code that I am trying to run. My aim is to grasp the meaning of this in different scopes and different types of invocations in Ja

3条回答
  •  猫巷女王i
    2020-12-10 22:21

    this in JavaScript refers to the object that you called a method on. If you invoke a function as someObject.functionName(args), then this will be bound to that object. If you simply invoke a bare function, as in functionName(args), then this will be bound to the window object.

    Inside of newF in the second example, you are shadowing the that variable in your inner function, but not passing anything into it, so it is undefined.

            var that = this;
            console.log(that);
            return function(that){
                console.log(that);
            }();
    

    You probably want the following instead, if you want something that is equivalent to your first example (passing that in to the inner function):

            var that = this;
            console.log(that);
            return function(that){
                console.log(that);
            }(that);
    

    Or the following, if you don't want to shadow it and just use the outer function's binding:

            var that = this;
            console.log(that);
            return function(){
                console.log(that);
            }();
    

提交回复
热议问题