私は 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