-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Function.prototype.bind()实现 #5
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
定义
MDN上对bind()函数的定义
这个定义充分的体现了翻译的苍白无力,再看英文
似乎也很迷
没关系,我来翻译成人话
更直观的Syntax描述
从中可以看出thisArg是必选项,
arg1, arg2, ...是可选项
它的返回值是A copy of the given function with the specified this value and initial arguments.
这样就很清楚了
举个栗子
你会得到一个异常
Uncaught TypeError: Illegal invocation
这是因为当函数不作为对象的属性被调用时,此时的this总是指向全局对象
当document.write被赋值给一个变量的时候,它的this就不再是document了
这时大家就会想,我可以call啊,可以apply啊
是的,这当然很可以,但是我就是不想改参数列表,想单独调用alwrite('hello') 这句呢,所以有
这时我们就能看出call、apply和bind的差异了:
bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 。
Function.prototype.bind的实现方式
大部分高级浏览器都实现了内置的bind,IE是>=9的版本才支持,在没有原生的Function.prototype.bind的引擎内,我们可以模拟一个。
低配实现
这时的bind函数才只能传一个上下文参数,还没有实现给新函数预先传入参数列表的功能
进化一点
把bind的参数从一个增加到多个,第一个参数为要绑定的上下文,其余为预先填入的新函数的参数
最后会把这部分参数和调用新函数时用户传入的参数组合成一个新的参数列表。
Referrence
JS中的call、apply、bind方法详解
MDN Function.prototype.bind()
Javascript设计模式和开发实践
The text was updated successfully, but these errors were encountered: