Apply/Call method in [removed] What is the first arguments “this”?

后端 未结 3 1841
失恋的感觉
失恋的感觉 2021-01-25 05:22

I am confused about using apply or call method correctly. I know that apply is passing an array to the function and call is passing strings to a function. For example the code b

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 05:38

    It's the context for the function. If you have this.something inside the function, it will access that particular property from that context object.

        
    
        function foo(bar) {
            this.bar = bar;
        }
        
        foo.apply(this, ['Hello']);    //calling foo using window as context (this = window in global context in browser)
        console.log(this.bar);         //as you can see window.bar is the same as this.bar
        console.log(window.bar);
        
        var ctx = {};    //create a new context
        
        foo.apply(ctx, ['Good night']);
        console.log(ctx.bar);        //ctx now has bar property that is injected from foo function
    Open up your dev console to see result.

    See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

提交回复
热议问题