Javascript Foncteur

Posté le mar. 04 avril 2017 dans blog

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 my_foncteur = new A_Foncteur();
my_foncteur.can_have_methods(42);
my_foncteur("Can be called like a function");

Implementing it in C++ is extremly easy, using operator overloading, so overloading 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:

/* Don't pollute global scope too much. */
window.your_scope = {};

your_scope.A_Function_Object = function()
{
  /* Prepare a closure */
  var that = this;
  this.some_data = "";

  this.foncteur = function()
  {
    /*
    ** Here, `this` is from the caller, we don't care about it,
    ** but the `that` is from the closure, so it's our `this`.
    */
    alert(that.some_data);
  }

  /*
  ** Add any function you need.
  */
  this.foncteur.set_data = function(data)
  {
    /*
    ** Same way to get "our" this from the closure.
    */
    that.some_data = data;
  }

  return (this.foncteur);
}

/* Enjoy */
var test = new your_scope.A_Function_Object();
test.set_data(42);
test();

Enjoy!