- 使用
Function.prototype.bind
进行兼容性处理:
- 在旧版IE浏览器中,
Function.prototype.bind
方法不存在,所以需要先进行兼容性的填充。
- 可以使用以下代码进行填充:
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this!== 'function') {
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () { },
fBound = function () {
return fToBind.apply(this instanceof fNOP? this : oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
function add(a, b) {
return a + b;
}
var safeAdd = add.bind(null);
// 然后将safeAdd传递给第三方库,这样在旧版IE等不支持bind原生实现的浏览器中也能确保函数正确传递和使用
- 使用
call
或 apply
进行替代(另一种思路):
- 当传递函数到第三方库时,可以通过创建一个包装函数,在包装函数内部使用
call
或 apply
来调用原始的 add
函数。
function add(a, b) {
return a + b;
}
function wrapperAdd() {
return add.apply(null, arguments);
}
// 将wrapperAdd传递给第三方库,在旧版IE浏览器中,通过apply也能正确调用add函数