Prototype's implementation of bind
from jquery ninja book
by dandoyon
HTML
<ul id="results"></ul>
CSS
#results li.pass { color: green; }
#results li.fail { color: red; }
JavaScript
function assert(value, desc) {
var li = document.createElement("li");
li.className = value ? "pass" : "fail";
li.appendChild(document.createTextNode(desc));
document.getElementById("results").appendChild(li);
}
// http://stackoverflow.com/questions/5145032/whats-the-use-of-array-prototype-slice-callarray-0
// the call to slice basically makes a shallow copy
Function.prototype.bind = function() {
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();
return function() {
return fn.apply(object, args.concat(Array.prototype.slice.call(arguments)));
};
};
var myObject = {};
function myFunction() {
return this === myObject;
}
assert(!myFunction(), "Context is not set yet");
var aFunction = myFunction.bind(myObject);
assert(aFunction(), "Context is set properly");