More conforming implementation of Function.prototype.bind
I had a hard time debugging why my specs were passing on the browser but failing on console, until I found the PhantomJS #10522 issue, and later found out that jasmine-rails already provides a bind shim (thus rendering my application's shim useless).
jasmine-rails' current shim might work for some cases (like #68), but it totally breaks my application. I tested MDN's first and simplest example, and it didn't work:
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(); // should be 81
Could we change the default shim to the one provided on MDN's page? I don't know if this will break @islandr's specs, but it seems to be a more conforming version. Here it is:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
Nice catch. Not sure how the bind implementation I used even allowed my specs to pass.
Here's the corrected implementation:
http://jsfiddle.net/jCpkH/
if (typeof Function.prototype.bind !== "function") {
Function.prototype.bind = function(context) {
var slice = Array.prototype.slice;
var fn = this;
return function() {
var args = slice.call(arguments, 1);
if (args.length) {
return arguments.length
? fn.apply(context, args.concat(slice.call(arguments)))
: fn.apply(context, args);
} else {
return arguments.length
? fn.apply(context, arguments)
: fn.call(context);
}
};
};
}