文章目录 1 手写call函数 2 手写apply函数 3 手写bind函数
1 手写call函数
call函数的实现步骤: 判断调用对象是否为函数。 判断传入上下文对象是否存在,如果不存在,则设置为window。 处理传入的参数,截取第一个参数后的所有参数。 将函数作为上下文对象的一个属性。 使用上下文对象来调用这个方法,并保存返回结果。 删除刚才新增的属性。 返回结果。
Function . prototype. myCall = function ( context ) { if ( typeof this !== "function" ) { console. error ( "type error" ) ; } let args = [ ... arguments] . slice ( 1 ) ; let result = null ; context = context || window; context. fn = this ; result = context. fn ( ... args) ; delete context. fn; return result;
} ;
2 手写apply函数
apply函数的实现步骤: 判断调用对象是否为函数。 判断传入上下文对象是否存在,如果不存在,则设置为window。 将函数作为上下文对象的一个属性。 判断参数值是否传入。 使用上下文对象来调用这个方法,并保存返回结果。 删除刚才新增的属性。 返回结果。
Function . prototype. myApply = function ( context ) { if ( typeof this !== "function" ) { throw new TypeError ( "Error" ) ; } let result = null ; context = context || window; context. fn = this ; if ( arguments[ 1 ] ) { result = context. fn ( ... arguments[ 1 ] ) ; } else { result = context. fn ( ) ; } delete context. fn; return result;
} ;
3 手写bind函数
bind 函数的实现步骤: 判断调用对象是否为函数。 保存当前函数的引用,获取其余传入参数值。 创建一个函数返回。 函数内部使用apply来绑定函数调用,需要判断函数作为构造函数的情况,这个时候需要传入当前函数的this给apply调用,其余情况都传入指定的上下文对象。
Function . prototype. myBind = function ( context ) { if ( typeof this !== "function" ) { throw new TypeError ( "Error" ) ; } let args = [ ... arguments] . slice ( 1 ) ; let fn = this ; return function Fn ( ) { return fn . apply ( this instanceof Fn ? this : context, args. concat ( ... arguments) ) ; } ;
} ;