Exemples de binding

Les boutons suivants permettent d'examiner le comportement de diverses situations quant au binding, c'est-à-dire la détermination du contexte (ou si vous préférez, du sens de this) dans une fonction JavaScript :

function f() {
    // this = objet window...
    this.alert('Oui, this est bien window !');
}
alert(this.navigator.userAgent); // this = objet window
f();

var myObj = {
    name: 'Mon objet à moi',
    method: function() {
        // Affiche le champ, car on est dans une méthode
        alert(this.name);
    }
}
myObj.method();
// Affichera autre chose, car ici this est l'objet window
alert(this.name);

var myObj = {
    name: 'Mon objet à moi',
    method: function() {
        alert(this.name);
    }
}

function f(fx) {
    fx();
}

f(myObj.method);

var myObj = {
    name: 'Mon objet à moi',
    method: function() {
        alert(this.name);
    }
}

function f(fx, obj) {
    fx.call(obj);
}

f(myObj.method, myObj);

var myObj = {
    name: 'Mon objet à moi',
    method: function(extraArg) {
        alert(this.name + '\n' + extraArg);
    }
}

Function.prototype.bind = function(obj) {
	var fx = this;
    return function() {
        return fx.apply(obj, arguments);
    }
}

function f(fx) {
    fx(42);
}

f(myObj.method.bind(myObj));