Thursday, December 13, 2012

[JS] Function Bind

Why you need this?
 var x = 9;
var module = {
  x: 81,
  getX: function() { return this.x; }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

// ----------------------------------------------------


Function.prototype.bind = function(oThis) {
  var args = Array.prototype.slice.call(arguments, 1);
  var fToBind = this;
  var fToReturn = function() {
    return fToBind.apply(oThis, args.concat(Array.prototype.slice.call(arguments)))
  }
  return fToReturn;
}

[JS] Function Currying

Currying allows you to easily create custom functions by partially invoking an existing function. Here’s a simple example:

var add = function(a,b) {
    return a + b;
}

//create function that returns 10 + argument
var addTen = add.curry(10);
addTen(20); //30

// ----------------------------------------

Function.prototype.curry = function() {
    if (arguments.length<1) {
        return this; //nothing to curry with - return function
    }
    var fToBind = this;
    var args = Array.prototype.slice.call(arguments); // Converting to array
    return function() {
        return fToBind.apply(this, args.concat(toArray(arguments)));
    }
}