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
if(typeofthis!=='function'){thrownewError('Function.prototype.bind - what is trying to be bound is not callable')}
最终代码
Function.prototype.bind2=function(context){if(typeofthis!=='function'){thrownewError('Function.prototype.bind - what is trying to be bound is not callable')}letself=this;letbindArgs=Array.prototype.slice.call(arguments,1);functionfbound(){letargs=Array.prototype.slice.call(arguments);returnself.apply(thisinstanceoffbound ? this: context,args.concat(bindArgs));}functionfNOP(){};fNOP.prototype=this.prototype;fbound.prototype=newfNOP();returnfbound;}
The text was updated successfully, but these errors were encountered:
Uh oh!
There was an error while loading. Please reload this page.
一句话介绍 bind:
bind() 方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )
由此我们可以首先得出 bind 函数的两个特点:
返回函数的实现方法
从第一个特点开始,举个例子:
此外,之所以
return self.apply(context)
,是考虑到绑定函数可能是有返回值的。同样是上面的例子,更改一下:传参的实现方法
接下来看一下第二点,可以传参,这里有两个问题,一个是bind 的时候传参,一个是 执行bind 返回函数的时候传参,是不是这两个地方都可以传参呢?先看一下实际bind 的使用:
函数需要传 name 和 age 两个参数,竟然还可以在 bind 的时候,只传一个 name,在执行返回的函数的时候,再传另一个参数 age!
这种情况我们使用 arguments 进行处理:
构造函数效果的实现方法
完成了这两点,最难的部分到啦!因为 bind 还有一个特点,就是
也就是说当 bind 返回的函数作为构造函数的时候,bind 时指定的 this 值会失效,但传入的参数依然生效。举个例子:
注意:尽管在全局和 foo 中都声明了 value 值,最后依然返回了 undefind,说明绑定的 this 失效了,如果了解 new 的实现,就会知道这个时候的 this 已经指向了 obj。
可以通过修改返回函数的原型实现:
构造函数的优化实现
但是在这个写法中,我们直接将 fBound.prototype = this.prototype,我们直接修改 fBound.prototype 的时候,也会直接修改绑定函数的 prototype。这个时候,我们可以通过一个空函数来进行中转:
容错处理
如果调用 bind 的不是 函数需要抛出错误:
最终代码
The text was updated successfully, but these errors were encountered: