Confusion with “this” object in JavaScript anonymous functions

前端 未结 3 1169
失恋的感觉
失恋的感觉 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条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 22:23

    In your second example, when you invoke the anonymous function, the parameter that is not defined (you aren't passing anything to it.) You can do this:

        newF: function()
        {
            var that = this;
            console.log(that);
            return function(that){
                console.log(that);
            }(that); // note that we are passing our 'that' in as 'that'
        }
    

    That will keep the proper value of the variable around.

    However, since you are scoping var that above, you could just remove the function parameter as well:

        newF: function()
        {
            var that = this;
            console.log(that);
            return function(){
                console.log(that);
            }(); // 'that' is referenced above.
        }
    

    As far as why anonymous functions have window as their this: whenever you call a function without a context (i.e. somef() vs context.somef()) this will point to the window object.

    You can override that and pass a this using .apply(context, argumentsArray) or .call(context, arg1, arg2, arg3) on a function. An example:

        newF: function()
        {
            console.log('Outer:', this);
            var innerF = function(){
                console.log('Inner:', this);
            };
            return innerF.apply(this,arguments);
        }
    

提交回复
热议问题