-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
面试官:bind、call、apply 区别?如何实现一个bind? #71
Comments
const name="lucy"; // 这里不会把name 挂到window上,改为var name 才可以
const obj={
name:"martin",
say:function () {
console.log(this.name);
}
};
obj.say(); //martin,this指向obj对象
setTimeout(obj.say,0); // window.name 不存在 这里应该稍微更正一下,const 后面的变量不会挂到window 对象上,所以this.name 不会是lucy |
|
new 调用 bind 后的函数,传递 new fn() 递归了呀 |
这个思路是啥 |
这个才是真正的手写一个bind |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
一、作用
call
、apply
、bind
作用是改变函数执行时的上下文,简而言之就是改变函数运行时的this
指向那么什么情况下需要改变
this
的指向呢?下面举个例子从上面可以看到,正常情况
say
方法输出martin
但是我们把
say
放在setTimeout
方法中,在定时器中是作为回调函数来执行的,因此回到主栈执行时是在全局执行上下文的环境中执行的,这时候this
指向window
,所以输出luck
我们实际需要的是
this
指向obj
对象,这时候就需要该改变this
指向了二、区别
下面再来看看
apply
、call
、bind
的使用apply
apply
接受两个参数,第一个参数是this
的指向,第二个参数是函数接受的参数,以数组的形式传入改变
this
指向后原函数会立即执行,且此方法只是临时改变this
指向一次当第一个参数为
null
、undefined
的时候,默认指向window
(在浏览器中)call
call
方法的第一个参数也是this
的指向,后面传入的是一个参数列表跟
apply
一样,改变this
指向后原函数会立即执行,且此方法只是临时改变this
指向一次同样的,当第一个参数为
null
、undefined
的时候,默认指向window
(在浏览器中)bind
bind方法和call很相似,第一参数也是
this
的指向,后面传入的也是一个参数列表(但是这个参数列表可以分多次传入)改变
this
指向后不会立即执行,而是返回一个永久改变this
指向的函数小结
从上面可以看到,
apply
、call
、bind
三者的区别在于:this
对象指向this
要指向的对象,如果如果没有这个参数或参数为undefined
或null
,则默认指向全局window
apply
是数组,而call
是参数列表,且apply
和call
是一次性传入参数,而bind
可以分为多次传入bind
是返回绑定this之后的函数,apply
、call
则是立即执行三、实现
实现
bind
的步骤,我们可以分解成为三部分:this
指向new
关键字整体实现代码如下:
The text was updated successfully, but these errors were encountered: