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".
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With