Function.prototype.bind在IE中不起作用,即使在它应该受支持的版本中也是如此

eve*_*Guy 5 javascript internet-explorer cross-browser

以下脚本在IE 9,IE 10,IE 11中不起作用

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

有没有解决方法呢?

编辑 - 链接问题中提供的MDN垫片不起作用!! 它们适用于IE 8!我对IE> 8的问题,其中Function.bind是"支持的".

Sco*_*pey 4

locationInternet Explorer 因允许您直接访问 Host 对象(例如和)而臭名昭著console,而没有像 Chrome 和 Firefox 那样在它们周围提供“Javascript 包装器”。

要模拟“绑定”功能,您必须使用包装函数,这不太漂亮,但可以完成这项工作:

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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

var locationToStringBound = bindHost(location, 'toString');
locationToStringBound();
Run Code Online (Sandbox Code Playgroud)