JavaScript中call()-apply()-bind()方法有什么不同?
发表于 2021-07-13 | 更新于 2023-03-18
总字数: 746 | 阅读时长: 3分钟 | 阅读量: 0
首先我写的代码,基本上就不会用到这3个方法。。。
但是也要明白它们有什么用,具体有什么区别,但我又不经常使用
学而不用,很快就会忘掉,所有就有了此篇短文
call()
- call()是一个方法,它是函数的方法
- call()可以调用函数
- call()可以改变this的指向
为什么会输出空字符串呢?因为this指向window,而window里有一个name属性
感兴趣的可以看看: JavaScript为什么会有name变量属性的问题
1 2 3 4 5
| fun() function fun(){ console.log(this) console.log(this.name) }
|
当使用call()后
上面第2点有提到:call()可以调用函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| function fun(){ console.log(this) console.log(this.name) } var lete = { name: 'Lete乐特' } fun.call(lete)
function fun(age,friend){ console.log(this) console.log(this.name) console.log(age,friend) } var lete = { name: 'Lete乐特' }
fun.call(lete,18,'小明')
|
apply()
apply()和call()方法一样,只是传入参数的方式分不同
apply()传参使用数组形式传入
1 2 3 4 5 6 7 8 9 10 11
| function fun(age,friend){ console.log(this) console.log(this.name) console.log(age,friend) } var lete = { name: 'Lete乐特' }
fun.apply(lete,[18,'小明'])
|
bind()
bind()和call()一模一样
bind()不会执行函数,而是返回函数的引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| function fun(age,friend){ console.log(this) console.log(this.name) console.log(age,friend) } var lete = { name: 'Lete乐特' }
var new_fun = fun.bind(lete,18,'小明') new_fun()
|
总结
call()
- 可以指定this指向
- 可以调用函数
- 它是函数的方法
- 第二个参数以后可以和正常函数一样传入原函数所需的参数
apply()
- 可以指定this指向
- 可以调用函数
- 它是函数的方法
- 第二个参数以后,需要使用数组传入原函数所需的参数
bind()
- 可以指定this指向
- 它是函数的方法
- 它和call()很像,但是bind()不会直接执行函数,而是返回函数的引用,需要定义变量来接收,然后调用这个变量才会执行这个函数