还在害怕手写题吗,本文可以帮你扩展并巩固自己的JS基础,顺便搞定90%的手写题。在工作中还可以对常用的需求进行手写实现,比如深拷贝、防抖节流等可以直接用于往后的项目中,提高项目开发效率。不说废话了,下面就直接上代码吧。

Function.prototype.myCall =function(context,...args){
let cxt = context || window;
//将当前被调用的方法定义在cxt.func上.(为了能以对象调用形式绑定this)//新建一个唯一的Symbol变量避免重复let func = Symbol()
    cxt[func] = this;
    args = args ? args : []
//以对象调用形式调用func,此时this指向cxt 也就是传入的需要绑定的this指向const res = args.length > 0 ? cxt[func](...args) : cxt[func]();
//删除该方法,不然会对传入对象造成污染(添加该方法)delete cxt[func];
return res;

2.apply的实现

Function.prototype.myApply =function(context,args = []){
let cxt = context || window;
//将当前被调用的方法定义在cxt.func上.(为了能以对象调用形式绑定this)//新建一个唯一的Symbol变量避免重复let func = Symbol()
    cxt[func] = this;
//以对象调用形式调用func,此时this指向cxt 也就是传入的需要绑定的this指向const res = args.length > 0 ? cxt[func](...args) : cxt[func]();
delete cxt[func];
return res;
}

3.bind的实现

需要考虑:

实现方法: