google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






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.


Label: OOP in JavaScript, JavaScript function context, JavaScript events, event handler

Free iPage Web Hosting for First Year NOW



If you're still looking for a reliable web host provider with affordable rates, why you don't take a little of time to try iPage, only with $1.89/month, included $500+ Free Extra Credits for the payment of 24 months ($45)?

Over 1,000,000+ existisng customers can not be wrong, definitely you're not, too! More important, when you register the web hosting at iPage through our link, we're going to be happy for resending a full refund to you. That's awesome! You should try iPage web hosting for FREE now! And contact us for anything you need to know about iPage.
Try iPage for FREE First Year NOW

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.

AIVideo-App.com
Generate your business videos by AI with voice or just text

chatGPTaz.com
Talk to ChatGPT by your mother language

AppAIVideo
Your first FREE AI Video App

Deepfake Video
Deepfake AI Video Maker

Deepfake
Deepfake AI Video Maker

AI Deep Fake
Deepfake AI Video Maker

AIvidio
AI Video Mobile Solutions

AIvideos
AI Video Platform & Solutions

AIvedio
AI Video App Maker

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Temu Free $500 for New Users
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Free TikTok Ads Credit
Master TikTok Ads for Your Business Marketing

Dall-E-OpenAI.com
Generate creative images automatically with AI

chatGPT4.win
Talk to ChatGPT by your mother language

First AI Product from Elon Musk - Grok/UN.com
Speak to Grok AI Chatbot with Your Language

Tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

iPhoneKer.com
Save up to 630$ when buy new iPhone 16

Buy Tesla Optimus Robot
Order Your Tesla Bot: Optimus Gen 2 Robot Today for less than $20k

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web