在 JavaScript 中,apply、bind 和 call 是用于改变函数执行上下文(即 this 关键字)的方法。它们在函数调用时非常有用。下面分别介绍这三个方法,并给出手写实现的代码。
1. apply
apply 方法调用一个函数,并显式地指定 this 的值和参数列表(以数组或类数组对象的形式)。
1 | function greet(greeting, punctuation) { |
2. call
call 方法与 apply 类似,也是调用一个函数,并显式地指定 this 的值和参数列表(以逗号分隔的形式)。
1 | function greet(greeting, punctuation) { |
3. bind
bind 方法创建一个新的函数,当这个新函数被调用时,其 this 值会被指定为 bind 方法的第一个参数,其余参数将作为新函数的参数。
1 | function greet(greeting, punctuation) { |
手写实现
下面是 apply、call 和 bind 的手写实现:
apply
1 | Function.prototype.myApply = function (context = window, args = []) { |
call
1 | Function.prototype.myCall = function (context = window, ...args) { |
bind
1 | Function.prototype.myBind = function (context, ...args) { |
示例
1 | function greet(greeting, punctuation) { |
对比
| 方法 | 是否调用 | 参数形式 |
|---|---|---|
apply |
是 | 数组或类数组对象 |
call |
是 | 逗号分隔的参数列表 |
bind |
否 | 逗号分隔的参数列表 |
通过这些手写实现,可以更好地理解 apply、call 和 bind 的内部工作原理。