《你不知道的JavaScript-上卷》第一部分-附录C-笔记-this词法

箭头函数

js 复制代码
var foo = a => {
    console.log( a );
};

foo( 2 ); // 2

箭头函数修复了this指向的一个问题。问题代码如下

js 复制代码
    var obj = {
      id: "awesome",
      cool: function coolFn() {
        console.log(this.id);
      }
    };
    var id = "not awesome"
    obj.cool(); // 酷
    setTimeout(obj.cool, 100); // 不酷 这里的this指向window,没有指向obj

旧的修复方式1,通过闭包来解决

  • 使用self变量引用声明时指向的this
js 复制代码
    var obj = {
      count: 0,
      cool: function coolFn() {
        var self = this;
        if (self.count < 1) {
          setTimeout(function timer() {
            self.count++;
            console.log("awesome?");
          }, 100);
        }
      }
    };
    obj.cool(); // awesome?

箭头函数也可以修复这个this绑定问题

  • 箭头函数在涉及 this 绑定时的行为和普通函数的行为完全不一致
  • 是用当前的词法作用域覆盖了 this 本来的值
  • 这个代码片段中的箭头函数"继承"了 cool() 函数的 this 绑定(因此调用它并不会出错)。
js 复制代码
    var obj = {
      count: 0,
      cool: function coolFn() {
        if (this.count < 1) {
          setTimeout(() => { // 箭头函数是什么鬼东西?
            this.count++;
            console.log("awesome?");
          }, 100);
        }
      }
    };
    obj.cool(); // awesome?

还有一种旧的修复方式,就是使用函数的bind方法,进行this绑定

js 复制代码
    var obj = {
      count: 0,
      cool: function coolFn() {
        if (this.count < 1) {
          setTimeout(function timer() {
            this.count++; // this 是安全的
            // 因为 bind(..)
            console.log("more awesome");
          }.bind(this), 100); // look, bind()!
        }
      }
    };
    obj.cool(); // more awesome
相关推荐
崔庆才丨静觅6 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60616 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了7 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅7 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅7 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅7 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment7 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅8 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊8 小时前
jwt介绍
前端
爱敲代码的小鱼8 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax