Function.prototype.myCall = function(ctx){
ctx ? Object(ctx) : window;
ctx.originFn = this; //this指向
var args = [];
for(var i = 1;i<arguments.length;i++){
args.push('arguments['+ i +']');
}
var res = eval('ctx.originFn('+args+')'); //平铺参数
delete ctx.originFn;
return res;
}
Function.prototype.myAppply = function(ctx,args){
ctx ? Object(ctx) : window;
ctx.originFn = this;
if(!args || myTypeOf(args) != 'array'){
return ctx.originFn();
}
if(myTypeOf(args) !=' array'){
throw new TypeError('Uncaught TypeError: CreateListFromArrayLike called on non-object');
}
var res = eval('ctx.originFn('+ args +')');
delete ctx.originFn;
return res;
}
function myTypeOf(val){
if(typeof val === null){
return 'null'
}
var result = Object.prototype.toString.call(val).slice(8, -1);
return {
Number: 'number',
Array: 'array',
String: 'string',
Object: 'object',
Null: 'object',
undefined: 'undefined',
Symbol: 'symbol',
Boolean: 'boolean',
Function: 'function'
}[result]
}
手写call,apply方法
于 2022-12-21 17:51:50 首次发布