我正在构建一个JavaScript本机函数补丁的集合,而且我有点坚持使用sh Function.prototype.apply
方法来解决旧问题(< = 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