您的位置:首页 > 移动开发

call、apply、bind

2020-08-23 21:24 1181 查看

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))
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: