call()
//初级版
Function.prototype.call = function call(context,...args){
let result;
context.xx = this;
result = context.xx(...args);
delete context.xx;
return result;
}
===============================================================
//中级版
Function.prototype.call = function call(context,...args){
let result,
key = Symbol('key') //保证属性的唯一性,防止有重名属性被覆盖
context[key] = this;
result = context[key](...args);
delete context[key];
return result;
}
===============================================================
//终极版
Function.prototype.call = function call(context,...args){
//如果为null 或 undefined,则指向window
context = context == null ? window:context;
//如果为基本数据类型,则转化为object(context)
if(!/^(object|function)$/i.test(typeof context)){
context = Object(context)
}
let result,
key = Symbol('key') //保证属性的唯一性,防止有重名属性被覆盖
context[key] = this;
result = context[key](...args);
delete context[key];
return result;
}
apply
和call
的区别仅仅是传参不同!apply
传数组
bind()
Function.prototype.bind = function bind(context,...outerArgs){
let _this = this;
return function(...innerArgs){
_this.call(context,...outerArgs.concat(innerArgs))
}
}