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
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.
Scope pertains to the visibility of the variables, and context refers to the object within which a function is executed.
Scope:In JavaScript, scope is achieved through the use of functions. When you use the keyword “var” inside of a function, the variable that you are initializing is private, and cannot be seen outside of that function. But, if there are functions inside of this function, then those “inner” functions can “see” that variable; that variable is said to be “in-scope”. Functions can “see” variables that are declared inside of them. They can also “see” any that are declared outside of them, but never those declared inside of functions that are nested in that function. This is scope in JavaScript.
Context:It refers to the object within which a function is executed. When you use the JavaScript keyword “this”, that word refers to the object that the function is executing in.