Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function.prototype.bind does not work in IE even in versions where it is supposed to be supported

The following script does not work in IE 9, IE 10, IE 11

var a = location;
var b = 'toString'
var c = a[b].bind(a);
c(); // "Invalid calling object in IE"

Any workarounds for this?

Edit - The MDN shim provided in the linked question do not work!! And they are for IE 8! My question for IE > 8 where Function.bind is "supported".

like image 551
everconfusedGuy Avatar asked Jul 29 '14 04:07

everconfusedGuy


2 Answers

Internet Explorer is notorious for giving you direct access to Host objects (like location and console), without providing a "Javascript wrapper" around them like Chrome and Firefox do.

To simulate the "bind" functionality, you'd have to use a wrapper function, which isn't pretty, but will do the job:

function bindHost(bindingContext, methodName) {
    return function(arg0, arg1, arg2) {
        if (arguments.length === 0) {
            bindingContext[methodName]();
        } else if (arguments.length === 1) {
            bindingContext[methodName](arg0);
        } else if (arguments.length === 2) {
            bindingContext[methodName](arg0, arg1);
        } else {
            // (Repeat the else-if blocks, if you require 3+ args)
        }
    }
}

And use it like this:

var locationToStringBound = bindHost(location, 'toString');
locationToStringBound();
like image 119
Scott Rippey Avatar answered Nov 10 '22 01:11

Scott Rippey


location is a host object - even in ES5 host objects are guaranteed to do only one thing - not follow the specification for normal JavaScript objects.

[It] is expected that the computational environment of an ECMAScript program will provide not only the objects and other facilities described in this specification but also certain environment-specific host objects, whose description and behaviour are beyond the scope of this specification except to indicate that they may provide certain properties that can be accessed and certain functions that can be called from an ECMAScript program. [emphasis added]

toString is not part of the guaranteed interface of all JS objects (including host objects) - therefore anything is possible, including, unfortunately the behavior you have described.

like image 42
Sean Vieira Avatar answered Nov 10 '22 01:11

Sean Vieira