example of Prototype binding

secrets of JS Ninja listing 5.9 creates a bind method on the Function prototype so that all it is easy to change the context on which something is operating

by Gerald Gillespie

HTML

<h2>results</h2>

<ul id="results"></ul>

CSS

#results li.pass {
    color : green;
}
#results li.fail {
    color : red;
}

JavaScript

console.clear();

var results;

this.assert = function assert(value, desc) {
    var li = document.createElement("li");
    li.className = value ? "pass" : "fail";
    li.appendChild(document.createTextNode(desc));
    results.appendChild(li);
    if (!value) {
        li.parentNode.parentNode.className = "fail";
    }
    console.log(desc,':',!!value);
    return li;
};

this.test = function test(name, fn) {
    results = document.getElementById("results");
    results = assert(true, name).appendChild(
    document.createElement("ul"));
    fn();
};

Function.prototype.bind = function(){                                     //#1
  var fn = this,  args = Array.prototype.slice.call(arguments),a = args.slice(0),
    object = args.shift();
  console.log(a,"\n", object, args);
    
  return function(){
    return fn.apply(object,
      args.concat(Array.prototype.slice.call(arguments)));
  };
};

var myObject = {};
function myFunction(){
  return this == myObject;
}

test('binding test begin', function(){
assert( !myFunction(), "Context is not set yet" );

var aFunction = myFunction.bind(myObject, 'arg1')
assert( aFunction(), "Context is set properly" );
});