var obj = {
a: 'xiao',
b: 'hong'
}
function test(){
console.log(this, arguments);
}
Function.prototype.myApply = function(ctx, args){
var ctx = ctx ? Object(ctx) : window;
ctx.originFn = this;
//如果不是object && fn , 证明是原始值抛出异常
if(typeof args !== 'object' && typeof args !== 'function'){
throw new TypeError('CreateListFromArrayLike called on non-object');
}
//不是数组执行原函数
if(!args || typeOf(args) !== 'Array'){
return ctx.originFn();
}
var ret = eval('ctx.originFn('+ args +')');
delete ctx.originFn;
//封装typeof方法
function typeOf(value){
if(value === 'null'){
return 'null';
}
return typeof(value) === 'object' ? {
'[object Object]': 'Object',
'[object Array]': 'Array',
'[object Number]': 'Number',
'[object Boolean]': 'Boolean',
'[object String]': 'String'
}[({}).toString.call(value)] : typeof(value);
}
return ret;
}
test.myApply(obj, [1, 2, 4]);
重写apply()方法
最新推荐文章于 2022-02-12 16:50:49 发布