我正在构建一组 JavaScript 原生函数补丁,并且我有点坚持使用Function.prototype.apply
旧 ies (<= v5) 的填充方法。我使用这段代码来支持.apply
方法,但我不完全确定它是否是“可行的”解决方案。欢迎提供一些反馈,谢谢。这是代码:
//
(function (pFunction, str, eval) {
// (string) Function Class: '[object Function]'
var funcstring = str.call(pFunction);
var isfunc = function (node) {
return funcstring === str.call(node);
};
// placeholder for private `.apply()` version
var _apply;
if (
// have `.apply()`?
!isfunc(pFunction.apply)
) {
_apply = function (self, arr) {
var func;
//`this` should be a Function{}
if (!isfunc(func = this))
throw TypeError('Function.prototype.apply called on incompatible ' + func);
// wrap primitives
var wrapper = Object(arr);
// throw for primitive argument,
// null/undefined are accepted by native `.apply()`
if (!(
(wrapper === arr) || (null == arr)
)) throw TypeError('second argument to Function.prototype.apply must be an array');
// build a string of `arr` argument
// that can be passed to `.eval()`
for (
var
it = -1, len = wrapper.length, args = [];
++it < len;
args.push('arr['+ it +']')
);
var code = args.length ?
'func.call(self,' + args.join(',') + ');':
'func.call(self);';
return eval(code);
};
pFunction.apply = function apply (self, arr) {
return _apply.call(this, self, arr);
};
}
})(
Function.prototype,
Object.prototype.toString,
eval
);
//eof