Search code examples
javascriptprototypecurrying

javascript, add function to prototype


In javascript, is possible add functions to a prototype with something similar to a curry?

I try with this code

var helloGoodBye = function (name, fun) {
  return function(message) {
    console.log('hello : ' + name);
    console.log(message);
    console.log('byebye : ' + name);
    return fun(message)
  }                                                                                           
}

var Machine = function (){
  this.state = 'green';
};

Machine.prototype = {
  green: helloGoodBye('green', function (message){
    this.state = 'red';
  }),
  red: helloGoodBye('red', function (message){
    this.state = 'green';
  })
}

var sm = new Machine();

sm[sm.state]('first message');
sm[sm.state]('second message');

and I get this output

"hello state: green"
"first message"
"byebye state: green"
"hello state: green"
"second message"
"byebye state: green"

but this way don't work, maybe because the this.state called in the functions is a this.state living in the global scope.


Solution

  • Yes, you just need to make the method invoke the fun callback on the receiver object. Use call:

    function helloGoodBye(name, fun) {
      return function(message) {
        console.log('hello : ' + name);
        console.log(message);
        console.log('byebye : ' + name);
        return fun.call(this, message);
    //            ^^^^^ ^^^^
      }                                                                                           
    }