通过简单示例了解 javascript 中的调用、应用和绑定
使用 javascript 时,您可能会遇到三种强大的方法:调用、应用和绑定。这些方法用于控制函数中 this 的值,从而更轻松地处理对象。让我们通过简单的示例来分解每种方法,以了解它们的工作原理。
1. 调用方法
call 方法允许您调用具有特定 this 值的函数并一一传递参数。
const person = { name: 'alice', greet: function(greeting) { console.log(`${greeting}, my name is ${this.name}`); }};const anotherperson = { name: 'bob' };person.greet.call(anotherperson, 'hello');// output: "hello, my name is bob"
登录后复制
在此示例中,调用将 this 值从 person 更改为 anotherperson,因此greet 函数打印“hello, my name is bob”。
2. 应用方法
apply 方法与 call 类似,但它以数组形式接收参数,而不是逐一接收参数。
const person = { name: 'alice', greet: function(greeting, punctuation) { console.log(`${greeting}, my name is ${this.name}${punctuation}`); }};const anotherperson = { name: 'charlie' };person.greet.apply(anotherperson, ['hi', '!']);// output: "hi, my name is charlie!"
登录后复制
这里,apply 还将 this 值更改为 anotherperson 并允许您将多个参数作为数组传递。
3. 绑定方法
bind 方法不会立即调用该函数。相反,它返回一个带有绑定 this 值的新函数,您可以稍后调用该函数。
const person = { name: 'Alice', greet: function() { console.log(`Hi, my name is ${this.name}`); }};const anotherPerson = { name: 'Diana' };const greetDiana = person.greet.bind(anotherPerson);greetDiana();// Output: "Hi, my name is Diana"
登录后复制
在此示例中,bind 创建了一个新函数greetdiana,并将其绑定到anotherperson。当您致电greetdiana 时,它会打印“嗨,我的名字是diana”。
立即学习“Java免费学习笔记(深入)”;
概括
call:立即调用具有特定 this 值和一一传递的参数的函数。apply:使用特定的 this 值和作为数组传递的参数立即调用函数。bind:返回一个具有特定 this 值的新函数,您可以稍后调用。
当您需要从一个对象借用方法以与另一个对象一起使用时,或者当您想要更好地控制函数中的 this 值时,这些方法非常方便。
以上就是通过简单示例了解 JavaScript 中的调用、应用和绑定的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2669922.html