Javascript Foncteur

May 8th, 2008 by Palard Julien

I just discovered, this morning, how to create a Visitor in Javascript :
A visitor is an objet who can be used like a function :

var mon_foncteur = new Un_Foncteur();
mon_foncteur.peut_avoir_des_methodes(42);
mon_foncteur("Peut etre appelle comme une fonction");

Download this code: js_foncteur.js

Implementing it in C++ is extremly easy, using operator overloading, so surcharging the () operator of an object, we have a visitor, but in Javascript, in the current version, we do not have operator overloading.
So we have the following trick :

/* Soyez propre, ne polluez pas le scope global */
window.votre_scope = {};

votre_scope.Un_Foncteur = function()
{
  /* On se prepare a faire une closure */
  var that = this;
  this.some_data = "";

  this.foncteur = function()
  {
    /*
    ** Ici le this est celui de l'appelant, il ne nous interesse probablement
    ** pas, le that est la closure, il nous permet de remonter vers notre this
    ** a nous, et d'y recuperer notre data.
    */
    alert(that.some_data);
  }

  /*
  ** On ajoute autant de methodes a notre foncteur que l'on desire
  */
  this.foncteur.set_data = function(data)
  {
    /*
    ** Idem pour la closure ici, on va chercher notre this, car le this d'ici
    ** est local a  la fonction
    */
    that.some_data = data;
  }

  return (this.foncteur);
}
/* Enjoy */
var test = new votre_scope.Un_Foncteur();
test.set_data(42);
test();

Download this code: js_foncteur2.js

Enjoy !

One Response to “Javascript Foncteur”

  1. Alex Says:

    Your blog is interesting!

    Keep up the good work!

Leave a Reply