Different in “scope” and “context” in this Javascript code

前端 未结 2 1540
暖寄归人
暖寄归人 2020-12-29 13:58

I\'m using this basic event system in my Javascript code and I\'m trying to document it for my coworkers. I\'m not really sure what the difference is in \"scope\" and \"con

2条回答
  •  执笔经年
    2020-12-29 14:18

    This code is unnecessarily confusing. The words context and scope are used to mean wrong things. First, let me explain what they should mean to every JavaScript developer:

    A context of a function is the value of this for that function -- i.e. the object the function is called as a method of.

    function F() { this.doSomething('good'); }
    

    You can invoke this function in different contexts like this:

    obj1 = { doSomething: function(x) { console.log(x); } }
    
    obj2 = { doSomething: function(x) { alert(x); } }
    
    F.call(obj1);
    F.call(obj2);
    

    There are many powerful programming patterns that emerge out of this. Function binding (Underscore bind or jQuery proxy) is one example.

    Scope on the other hand defines the way JavaScript resolves a variable at run time. There is only two scopes in JavaScript -- global and function scope. Moreover, it also deals with something called "scope chain" that makes closures possible.


    Your on method saves the variable scope and then uses it in the trigger function as context, which is confusing (it shouldn't be named scope -- it's the context):

    handler.method.call(
        handler.scope, this, type, data
    )
    

    And I have no idea what this is in the above call.

    The on method also accepts a context which defaults to the supplied scope in case context is falsy. This context is then used to filter the functions to call in trigger.

    context !== handler.context
    

    This lets you group your handlers by associating them with an arbitrary object (which they have called context) and then invoke the entire group by just specifying the context.

    Again, I think this code is overly convoluted and could have been written in a lot simpler way. But then, you shouldn't need to write your own event emitters like this in the first place -- every library has them ready for your use.

提交回复
热议问题