You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。
Function.prototype.bind2=function(){varthatFun=this;varcontext=arguments[0];varargs=Array.prototype.slice.call(arguments,1);varfBound=function(){varnewArgs=args.concat(Array.prototype.slice.call(arguments))returnthatFun.apply(thisinstanceoffBound ? this : context,newArgs)}fBound.prototype=this.prototypereturnfBound;}
模拟实现第三部-优化
//调用 bind 的不是函数if(typeofthis!=="function"){thrownewError("Function.prototype.bind - what is trying to be bound is not callable");}varthatFun=this;varcontext=arguments[0];varargs=Array.prototype.slice.call(arguments,1);varfNOP=function(){};varfBound=function(){varnewArgs=args.concat(Array.prototype.slice.call(arguments))returnthatFun.apply(thisinstanceoffBound ? this : context,newArgs)}fNOP.prototype=this.prototypefBound.prototype=newfNOP();returnfBound;}
bind()
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
模拟实现第一步
模拟实现第二步、
当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。
模拟实现第三部-优化
生产使用
或者
MDN Function.prototype.bind()
JavaScript深入之bind的模拟实现
The text was updated successfully, but these errors were encountered: