google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Contexting POO en JavaScript Dans ce tutoriel JavaScript libre de HTML, l'auteur examine le contexte et la port


�tiquette: POO en JavaScript, contexte fonction JavaScript, d'

Gratuit iPage h�bergement Web pour la premi�re ann�e MOMENT



Si vous �tes toujours � la recherche d'un fournisseur d'h�bergement Web fiable avec des tarifs abordables, pourquoi vous ne prenez pas un peu de temps pour essayer iPage, seulement avec $1.89/month, inclus $500+ Cr�dits suppl�mentaires gratuites pour le paiement de 24 mois ($45)?

Plus de 1.000.000 de clients + existisng peuvent pas avoir tort, vraiment vous n'�tes pas aussi! Plus important encore, lorsque vous enregistrez l'h�bergement web � iPage gr�ce � notre lien, nous allons �tre heureux de renvoyer un plein remboursement. C'est g�nial! Vous devriez essayer iPage h�bergement web GRATUITEMENT maintenant! Et contactez-nous pour tout ce que vous devez savoir sur iPage.
Essayez iPage GRATUIT premi�re ann�e MOMENT

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
Générez vos vidéos d'entreprise par l'IA avec la voix ou simplement du texte

chatGPTaz.com
Parlez à ChatGPT dans votre langue maternelle

AppAIVidéo
Votre première application vidéo AI GRATUITE

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 en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Temu gratuit 500 $ pour les nouveaux utilisateurs
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Crédits publicitaires TikTok gratuits
Maîtrisez les publicités TikTok pour le marketing de votre entreprise

Dall-E-OpenAI.com
Générez automatiquement des images créatives avec l'IA

chatGPT4.win
Parlez à ChatGPT dans votre langue maternelle

Premier produit d'intelligence artificielle d'Elon Musk - Grok/UN.com
Parlez au chatbot Grok AI dans votre langue

Outily.win
Centre d'outils ouvert et gratuit, utilisable par tous et pour tous, avec des centaines d'outils

GateIO.gomymobi.com
Airdrops gratuits à réclamer et à partager jusqu'à 150 000 $ par projet

iPhoneKer.com
Économisez jusqu'à 630 $ à l'achat d'un nouvel iPhone 16

Acheter le robot Tesla Optimus
Commandez votre robot Tesla Bot : Optimus Gen 2 dès aujourd'hui pour moins de 20 000 $

JavaScript par jour


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web