本文首发于 JS:call、bind 和 apply
前言
在了解 call、bind 和 apply 之前,需要先了解什么是 this。
什么是 this ?
this 代表函数的执行环境,即函数执行的上下文。
比如在浏览器中执行下面这段代码,this 就是 Window 对象。
function foo() {
console.log(this)
}
foo() // Window
下面这段代码的 this 则是指 Tom 对象。
const Tom = {
name: 'Tom',
say: function () {
console.log(this) // {name: 'Tom', say: ƒ}
},
}
Tom.say()
call、bind 和 apply 都是改变函数的 this 指向的方法,但是在使用上有所区别,具体表现为参数传递和如何执行。

call()
call() 方法用于调用一个函数。call() 的第一个参数将作为这个新函数的 this,而其余参数将作为新函数的参数(使用逗号隔开)。
function foo(x, y, z) {
console.log(x, y, z)
}
foo.call(null, 1, 2, 3) // 1 2 3
function Student(name, age) {
this.name = name
this.age = age
}
function MiddleSchoolStudent(name, age) {
Student.call(this, name, age)
this.education = 'Middle School'
}
let tom = new MiddleSchoolStudent('Tom', 15)
console.log(tom) // MiddleSchoolStudent{name: "Tom", age: 15, education: "Middle School"}
bind()
bind() 方法返回一个新的函数。和 call() 一样,bind() 的第一个参数将作为这个新函数的 this,而其余参数将作为新函数的参数(使用逗号隔开)。
const student = {
age: 15,
getAge: function () {
return this.age
},
}
const getAge = student.getAge
console.log(getAge()) // undefined
const getStudentAge = getAge.bind(student)
console.log(getStudentAge()) // 15
apply()
apply() 方法和 call() 一样用于调用一个函数。第一个参数作为这个新函数的 this,和 call() 的区别在于,call() 的剩余参数以逗号隔开,而 apply() 的则是一个数组。
const ages = [15, 16, 12, 13, 17]
const max = Math.max.apply(null, ages)
console.log(max) // 17
参考资料:
网友评论