- 手写call
Function.prototype.call = function(context,...args){
if(typeof this != 'function'){
throw new TypeError('not Function');
}
var context = context || window;
context.fn = this;
var result = context.fn(...args);
delete context.fn;
return result;
}
- 手写apply
Function.prototype.apply = function(context, args = []){
if(typeof this != 'function'){
throw new TypeError('not Function')
}
var context = context || window;
context.fn = this;
var result = context.fn(...args);
delete context.fn;
return result;
}
- 手写bind:与前两个区别主要是bind是返回一个函数,函数内部的this需要先在外部保存,context.fn = _self,是将调用bind的函数作为当前context的一个属性
Function.prototype.bind = function(context,...args){
if(type != 'function'){
throw new TypeError('not Function');
}
var context = context || window;
var _self = this;
return function(...args1){
context.fn = _self;
let result = context.fn(...[...args1,...args]);
delete context.fn
return result;
}
}