apply、call、bind
Mark Peng 10/18/2022 JavaScriptthis
# 作用
apply、call、bind的作用是改变函数的执行上下文,也就是改变函数运行时的this指向。
# 区别
window.color = 'blue'
let o = {
color: 'red'
}
function fn(num1, num2) {
console.log(this.color)
return num1 + num2
}
fn(1, 2) // blue 3
fn.apply(o, [1, 2]) // red 3
fn.call(o, 1, 2) // red 3
let oFn = fn.bind(o)
oFn(1, 2) // red 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
call() 方法与 apply() 的作用一样,只是传参的形式不用。第一个参数都是this值,接下来 apply() 会传入参数的数组,而 call() 传给被调用函数的参数是逐个传递的,必须是将参数一个个列出来。 bind() 方法的话会创建一个新的函数实例,其 this 值会被绑定到传给 bind() 的对象。