Function.prototype.call1 = function(context,...args){
// context 为传入的this 指向
// context 传入为空的时候this指向默认为全局
if(context==null) context = globalThis;
if(context!=='object') context = new Object(context) //值类型转对象
const fnKey = Symbol(); //唯一标识
// 给当前对象添加函数
context[fnKey] = this;//this为当前函数
const res = context[fnKey](...args) //绑定了 this
delete context[fnKey] //清理掉 防止污染
return res;
}
function fn( a,b,c){
console.log(this,a,b,c)
}
fn.call1({x:2},10,20,60)
JavaScript 手写call 函数
最新推荐文章于 2024-05-05 14:51:09 发布