Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different in "scope" and "context" in this Javascript code

Tags:

javascript

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 "context" in this code. Can anyone help me understand why I even need them both?

this.myClass.prototype.on = function (type, method, scope, context) {
    var listeners, handlers, scope;
    if ( !(listeners = this.listeners) ) {
        listeners = this.listeners = {};
    }

    if ( !(handlers = listeners[type]) ) {
        handlers = listeners[type] = [];
    }

    scope = (scope ? scope : window);
    handlers.push({
        method: method,
        scope: scope,
        context: (context ? context : scope)
    });
}

this.myClass.prototype.trigger = function(type, data, context) {
    var listeners, handlers, i, n, handler, scope;
    if (!(listeners = this.listeners)) {
        return;
    }
    if (!(handlers = listeners[type])){
        return;
    }
    for (i = 0, n = handlers.length; i < n; i++){
        handler = handlers[i];
        if (context && context !== handler.context) continue;
        if (handler.method.call(
            handler.scope, this, type, data
        )===false) {
            return false;
        }
    }
    return true;
}
like image 816
James P. Wright Avatar asked Jan 14 '13 16:01

James P. Wright


People also ask

What are the different scopes in JavaScript?

JavaScript has 3 types of scope: Block scope. Function scope. Global scope.

What is context in JavaScript?

In JavaScript, “context” refers to an object. Within an object, the keyword “this” refers to that object (i.e. “self”), and provides an interface to the properties and methods that are members of that object. When a function is executed, the keyword “this” refers to the object that the function is executed in.

What is the difference between scope and function?

The scope determines the accessibility of variables and other resources in the code, like functions and objects. JavaScript function scopes can have two different types, the locale and the global scope. Local variables are declared within a function and can only be accessed within the function.

What is the difference between scope and closure in JavaScript?

When you declare a variable in a function, you can only access it in the function. These variables are said to be scoped to the function. If you define any inner function within another function, this inner function is called a closure. It retains access to the variables created in the outer function.


2 Answers

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 are only two four scopes in JavaScript -- global, function, block, and module scopes. 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.

like image 65
treecoder Avatar answered Oct 22 '22 09:10

treecoder


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.

like image 45
Nikhil Avatar answered Oct 22 '22 09:10

Nikhil