apply
Function.prototype.myCall = function (context, args = []) {// 判断调用该方法的对象是否是函数if (typeof this !== "function") {throw new TypeError(`It's must be a function`);}// context 不存在,或者传递的是 null undefined,则默认为 windowcontext = context || window// 指定唯一属性,防止 delete 删除错误const fn = Symbol();// this 是调用 myCall 的函数context[fn] = this;// 调用 context 的 fnconst result = context[fn](...args);// 删除掉 context 新增的属性delete context[fn];// 将结果返回return result;};
bind
bind() 会返回一个新函数
Function.prototype.myBind = function (context, ...args) {const fn = thisif (typeof fn !== 'function') {throw new TypeError('It must be a function')}context = context || windowreturn function (...otherArgs) {return fn.apply(context, [...args, ...otherArgs])}}
call
apply() 第二个参数接收的是一个数组, call() 接收的是一个参数列表
Function.prototype.myCall = function (context, ...args) {// 判断调用该方法的对象是否是函数if (typeof this !== "function") {throw new TypeError(`It's must be a function`);}// context 不存在,或者传递的是 null undefined,则默认为 windowcontext = context || window// 指定唯一属性,防止 delete 删除错误const fn = Symbol();// this 是调用 myCall 的函数context[fn] = this;// 调用 context 的 fnconst result = context[fn](...args);// 删除掉 context 新增的属性delete context[fn];// 将结果返回return result;};
