Confusion with “this” object in JavaScript anonymous functions

前端 未结 3 1172
失恋的感觉
失恋的感觉 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:44

    In your first code example, the anonymous function, though declared within a function that is a member of the someStuff object, is not a member of the someStuff object. For that reason, this in that function is a reference to the window object. If you wanted to invoke the anonymous function and have control over the this reference, you could do the following:

    var someStuff = {
        doofus:"whatever",
        newF: function()
        {
            var that = this;
            console.log(that);
            var innerStuff = function(){
                console.log(this);
            };
    
            return innerStuff.apply(this);
        }
    }
    
    someStuff.newF();
    

    In your second example, your actually creating an anonymous function, executing it, and then returning the value that the anonymous function returned. However, your anonymous function did not return anything. Additionally, you have a variable name conflict. You could do:

    var someStuff = {
        doofus:"whatever",
        newF: function()
        {
            var that = this;
            console.log(that);
            return function(){
                console.log(that);
                return true;
            }();
        }
    }
    
    someStuff.newF();
    

    I added the return true because your function should return something, since the function that is executing it is returning the return value of the anonymous function. Whether it returns true or false or a string or an object or whatever else depends on the scenario.

提交回复
热议问题