Skip to content
This repository has been archived by the owner on Jan 10, 2024. It is now read-only.

More conforming implementation of Function.prototype.bind #74

Open
eshiota opened this issue Oct 7, 2013 · 1 comment
Open

More conforming implementation of Function.prototype.bind #74

eshiota opened this issue Oct 7, 2013 · 1 comment

Comments

@eshiota
Copy link

eshiota commented Oct 7, 2013

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

@rymohr
Copy link
Contributor

rymohr commented Oct 8, 2013

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);
            }
        };
    };
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants