个人技术站点JASONWU

Keep Coding


  • 主页

  • 文章

  • 搜索

JavaScript 函数中的 this 值

新建: 2021-05-29 编辑: 2021-06-21   |   分类: JavaScript   | 字数: 803 字

动态修改 JS 函数中的 this 值。

通用代码片段

JavaScript
 1const jsCourse = {
 2  subject: 'JavaScript',
 3  description: '一门流行的前端编程语言',
 4  people: 0,
 5
 6  score(like, stars) {
 7    console.log(`${this.subject}:${this.description}
 8已有${++this.people}人评价,\
 9您的评价为:${like ? '👍' : '👎'} ${'⭐️'.repeat(stars)}`);
10  }
11};
12
13jsCourse.score(false, 3);
14// JavaScript:一门流行的前端编程语言
15// 已有1人评价,您的评价为:👎 ⭐️⭐️⭐️
16
17const nodeCourse = {
18  subject: 'Node.js',
19  description: '后端 JS 运行环境',
20  people: 0
21};

Function.prototype.call()

语法:

JavaScript
1call()
2call(thisArg)
3call(thisArg, arg1, ..., argN)

示例:

JavaScript
1// 将 `jsCourse.score` 作为 `nodeCourse` 的方法使用
2jsCourse.score.call(nodeCourse, true, 5);
3// Node.js:后端 JS 运行环境
4// 已有1人评价,您的评价为:👍 ⭐️⭐️⭐️⭐️⭐️

Function.prototype.apply()

语法:

JavaScript
1apply(thisArg)
2apply(thisArg, argsArray)

示例:

JavaScript
1// 将 `jsCourse.score` 作为 `nodeCourse` 的方法使用
2jsCourse.score.apply(nodeCourse, [true, 5]);
3// Node.js:后端 JS 运行环境
4// 已有1人评价,您的评价为:👍 ⭐️⭐️⭐️⭐️⭐️

apply 和 call 除了第二个参数不同外,其他没有任何区别。可通过 Spread 语法统一都使用 call:

JavaScript
1jsCourse.score.call(nodeCourse, ...[true, 5]);

Function.prototype.bind()

语法:

JavaScript
1bind(thisArg)
2bind(thisArg, arg1, ..., argN)

示例:

JavaScript
 1const scoreNode = jsCourse.score.bind(nodeCourse);
 2
 3scoreNode(true, 4);
 4// Node.js:后端 JS 运行环境
 5// 已有1人评价,您的评价为:👍 ⭐️⭐️⭐️⭐️
 6
 7// Partial application
 8const scoreNodeLike = jsCourse.score.bind(nodeCourse, true);
 9
10scoreNodeLike(5);
11// Node.js:后端 JS 运行环境
12// 已有2人评价,您的评价为:👍 ⭐️⭐️⭐️⭐️⭐️

bind 方法还常用于事件监听器:

JavaScript
 1const electronCourse = {
 2  subject: 'Electron',
 3  likes: 0,
 4
 5  like() {
 6    console.log(this);
 7
 8    console.log(`${this.subject},点赞数 👍:${++this.likes}`);
 9  }
10}
11
12document.querySelector('.btn-like').addEventListener(
13  'click', electronCourse.like.bind(electronCourse)
14);
15// Object {subject: "Electron", likes: 0, like: ƒ}
16// Electron,点赞数 👍:1

由于事件处理函数会绑定自己的 this 值。因此下面代码是错误的,其中 this 的值为 HTML Button 元素:

JavaScript
1document.querySelector('.btn-like')
2  .addEventListener('click', electronCourse.like);
3// <button class="btn-like">喜欢</button>
4// undefined,点赞数 👍:NaN
#this#

文章:JavaScript 函数中的 this 值

链接:https://www.wuxianjie.net/posts/js-function-this/

作者:吴仙杰

文章: 本博客文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议,转载请注明出处!

JavaScript 构建 Promise
JavaScript 异步 vs 同步
  • 文章目录
  • 站点概览
吴仙杰

吴仙杰

🔍 Ctrl+K / ⌘K

27 文章
9 分类
25 标签
邮箱 GitHub
  • 通用代码片段
  • Function.prototype.call()
  • Function.prototype.apply()
  • Function.prototype.bind()
© 2021-2025 吴仙杰 保留所有权利 All Rights Reserved
浙公网安备 33010302003726号 浙ICP备2021017187号-1
0%