Understanding $.proxy() in jQuery

前端 未结 4 906
陌清茗
陌清茗 2020-11-29 14:39

From docs I understand that .proxy() would change the scope of the function passed as an argument. Could someone please explain me this better? Why should we do

4条回答
  •  执念已碎
    2020-11-29 15:21

    Without going into greater detail (which would be necessary because this is about Context in ECMAScript, the this context variable etc.)

    There are three different types of "Contexts" in ECMA-/Javascript:

    • The global context
    • Function context
    • eval context

    Every code is executed in its execution context. There is one global context and there can be many instances of function (and eval) contexts. Now the interesting part:

    Every call of a function enters the function execution context. An execution context of a function looks like:

    The Activation Object
    Scope Chain
    this value

    So the this value is a special object which is related with the execution context. There are two functions in ECMA-/Javascript which may change the this value in a function execution context:

    .call()
    .apply()
    

    If we have a function foobar() we can change the this value by calling:

    foobar.call({test: 5});
    

    Now we could access in foobar the object we passed in:

    function foobar() { 
        this.test // === 5
    }
    

    This is exactly what jQuery.proxy() does. It takes a function and context (which is nothing else than an object) and links the function by invoking .call() or .apply() and returns that new function.

提交回复
热议问题