马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在 JavaScript 中,`call`、`apply` 和 `bind` 是 Function 对象的三个紧张方法,它们都与函数的上下文(`this` 值)和参数通报有关。
一、`call` 方法
1. 语法
- function.call(thisArg, arg1, arg2, ...)
复制代码 2. 示例代码
- const person = {
- name: "John",
- greet: function (message) {
- console.log(`${message}, ${this.name}`);
- },
- };
- const anotherPerson = {
- name: "Jane",
- };
- // 使用 call 方法调用 greet 函数,并指定 this 为 anotherPerson
- person.greet.call(anotherPerson, "Hello");
- // 最终输出 `Hello, Jane`。
复制代码 二、`apply` 方法
1. 语法
- function.apply(thisArg, [argsArray])
复制代码 2. 示例代码
- const numbers = [5, 6, 2, 3, 7];
- // 使用 Math.max 函数找出数组中的最大值
- const max = Math.max.apply(null, numbers);
- console.log(max);
- // 最终输出 7。
复制代码 三、`bind` 方法
1. 语法
- function.bind(thisArg, arg1, arg2, ...)
复制代码 2. 示例代码
- const person = {
- name: "John",
- greet: function (message) {
- console.log(`${message}, ${this.name}`);
- },
- };
- const anotherPerson = {
- name: "Jane",
- };
- // 使用 bind 方法创建一个新的函数,并指定 this 为 anotherPerson
- const newGreet = person.greet.bind(anotherPerson);
- // 调用新函数
- newGreet("Hi");
复制代码 四、三者的区别
1. 调用方式
`call` 和 `apply` 会立即调用函数,而 `bind` 会返回一个新的函数,必要手动调用这个新函数。
2. 参数通报方式
`call` 方法担当多个参数,参数之间用逗号分隔。
`apply` 方法担当两个参数,第二个参数是一个数组或类数组对象,数组中的元素会作为参数通报给函数。
`bind` 方法可以在创建新函数时预设一些参数,这些参数会在调用新函数时作为前置参数。
五、使用场景
1. `call` 和 `apply`
当必要在调用函数时动态改变 `this` 值,并且已知参数数量时,使用 `call` 方法。
当必要通报的参数存储在数组中时,使用 `apply` 方法,例如调用 `Math.max` 或 `Math.min` 函数处置惩罚数组元素。
2. `bind`
当必要创建一个新函数,并且希望这个新函数始终具有特定的 `this` 值时,使用 `bind` 方法。常见于变乱处置惩罚函数中,确保 `this` 指向正确的对象。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |