facebook@jsbanktwitter@js_bankgoogle+javascriptbanknewsletterrss@jsbank
Guest, register






ieoBIN.com - The Best IEO List to Discover, Invest in 2019

Contexting OOP in JavaScript In this free HTML JavaScript tutorial, the author discusses context and scope within OOP in JavaScript with some topics: JavaScript functions context are first class objects, Default context, Context and JavaScript event handlers, Changing the context using Function.apply() and Function.call(), Using Function.call() to solve the event handler problem.


In the previous examples you might have noticed that we use this to get a reference to the object that a function belongs to while we're inside the function. The value of the this operator is the context of the method:

function Pet(name, species, hello){
    this.name = name;
    this.species = species;
    this.hello = hello;
    this.sayHello = function()
    {
        alert(this.hello);
    }
}
var rufus = new Pet("Rufus", "cat", "miaow");

If you're familiar with languages like C# or Java, chances are you've never really thought too much about this because its value always references the object that the method belongs to (the rufus object in the previous example). This is usually the case in javascript too but there are some situations where it won't refer back to the object that you're expecting.

Functions are first class objects

The difference between way the this operator works in C# and javascript is a side effect of functions being first class objects in javascript. Functions are just another type of variable that can be passed around the application.

The methods in a javascript object are only methods because you chose to store a function inside one of the object's properties. There is nothing in the language that always binds the method to the object. If you wanted to, you could use the same function in a number of different objects:

var sayHello = function()
{
    alert(this.name + " says hello");
}

var rufus = {
    name: "Rufus"
}
rufus.sayHello = sayHello;

var sabby = {
    name: "Sabby"
}
sabby.sayHello = sayHello;

// invoke sayHello from the objects
rufus.sayHello();
sabby.sayHello();

Complete example

Notice that the context of the sayHello() function (the thing that this references) is different depending on which object invoked it. In this example the two different objects were pretty much the same but the sayHello() function could be used by completely different objects as long as they provide the right information.

This design decouples the function from the context that uses it. You can plug any context into the function and it will still work. This is one of the reasons that having functions as first class objects is such a powerful feature.

Default context

Every time you call a function it has a context even if it is not explicitly provided. If no context is explicitly provided when the function is called, the default context will be used instead. In the browser the default context is the window object. This means that if you call a function without invoking it through an object, this will be set to the window.

To see this in action lets try calling sayHello() without invoking it from an object:

var sayHello = function()
{
 if(this.name)
  alert(this.name + " says hello");
 else    
  alert(this + " can't say hello because name property was not set");
}

// invoke sayHello from the global context
sayHello();

Complete example

Javascript is happy to run the function without calling it through an object. It just sets the context to the default context, the window object. The window object doesn't have a name property so instead of alerting "someone says hello", instead it alerts the error message about the object not having a name property.

The way I imagine it is calling sayHello() is really calling window.sayHello(). You just don't need to explicitly use the window object to invoke it because the window object is the default context. The same thing happens if you set a variable without declaring it first using the var statement. Instead of creating a new variable that's only available in the current scope, it actually creates a new property on the window object:

flibble = "xyz";
alert(window.flibble);

Complete example

Check out this article if you want to find out more about what happens when a Javascript function is called. It's a really interesting write up that goes into lots of detail.

Context and event handlers

In the previous examples, we have explicitly called the sayHello() method ourselves. This doesn't happen for functions that are used for event handlers. We wire them up and then they are invoked automatically when the event occurs.

This can be a problem for functions that actually are methods of objects. The logic that invokes the event handler doesn't know anything about the object the method belongs to so it can't be invoked in the right context.

Instead the context of the method is set to the element that caused the event. If it was a button click event, it will be set to the HTML button element that was clicked. It it is an onload event, it will be set to the element that was loaded. The exception to this rule is IE where the context will always be set to the default window context.

Here's another example which uses the sayHello function as an event handler:

var sayHello = function()
{
 if(this.name)
  alert(this.name + " says hello");
 else
  alert(this + " can't say hello because name property was not set");
}

// invoke sayHello by clicking the button
document.getElementById("button").onclick = sayHello;

Complete example

Changing the context using Function.apply() and Function.call()

In cases like the event handler problem, you might want to invoke a method in an explicit context. Javascript functions support two methods that you can use to do this called Function.apply and Function.call.

Both methods are pretty much the same. You can use them both to invoke a method, supply the context and a list of parameters. The only difference between the two are the way the parameters are passed in. Function.apply() accepts the parameters for the function as an array while Function.call() accepts them as individual parameters:

var sayHello = function()
{
    if(this.name)
        alert(this.name + " says hello");
    else
        alert(this + " can't say hello because name property was not set");
}

var rufus = {
    name: "Rufus"
}

sayHello.call(rufus);
sayHello.apply(rufus);

Complete example

Using Function.call() to solve the event handler problem

We can use Function.call() to invoke the event handler in the right context. The plan: create a function that wires up the event handler and knows what the context of the function should be when the event is run:

function addEvent(element, eventName, handler, context)
{
    var wrapper = handler;
    if(context)
    {
        // uses a closure to access the context object
        wrapper = function(e) {
            handler.call(context, e);
        }
    }
    if(element.addEventListener)
        element.addEventListener(eventName, wrapper, false);
    else if(element.attachEvent)
        element.attachEvent("on" + eventName, wrapper);
}

addEvent(document.getElementById("button"), "click", sayHello, rufus);

Complete example

The trick to this is to create a new wrapper anonymous function that calls the handler in the right context and can be passed to the addEventListener() method. If a context is passed in, the anonymous function is called instead of the event handler and runs the actual event handler in the right context.

Javascript has a feature called closures so when you create an anonymous function inside another function, you can access local variables from the parent function. We can use this to reference the function context object when the anonymous function is run.

If you're an ASP.NET ajax programmer, this is exactly what happens when you use Function.createDelegate() to register an event handler inside an component.

What's next?

Sometimes you need to find out things about an object's capabilities. The next article talks about finding out what type of object you have and what it can do.

This article is part of a set of related posts about How javascript objects work.

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web