javascript - typescript : fat arrow & this scope relation

标签 javascript typescript ecmascript-6 this

我正在练习下面的代码 代码引用:Link

   let obj = {
    name : "Cj",   
    sayLater : function(){
        setTimeout(function(){
          console.log("sayLater :> "+this.name); 
        },3000)
    },
    sayNow : function(){
      console.log("sayNow :> "+this.name); 
    },
    sayLaterFA : function(){
      setTimeout(() => console.log("sayLaterFA :> "+this.name) ,3000)
    },
    sayNowFA : () => console.log("sayNowFA :> "+this.name),
    sayLaterPureFatArrow : () => { setTimeout(() => console.log("sayLaterPureFatArrow :> "+this.name),4000) },
    sayNowPureFatArrow : () => { console.log("sayNowPureFatArrow :> "+this.name) }
  }



 obj.sayLater();             //Output : sayLater :> undefined
  obj.sayNow();               //Output : sayNow :> Cj
  obj.sayLaterFA();           //Output : sayLaterFA :> Cj 
  obj.sayNowFA();             //Output : sayNowFA :> Cj
  obj.sayLaterPureFatArrow(); //Output : sayLaterPureFatArrow :> undefined 
  obj.sayNowPureFatArrow();   //Output : sayNowPureFatArrow :> undefined

任何人都可以解释一下为什么我使用胖箭头函数时输出未定义

最佳答案

这些箭头函数的 this 值是创建函数的上下文中的 this 值。这不是您正在构造的对象;它就是对象初始值设定项代码所在的 this 所在的位置。

换句话说,在里面

let obj = {
  // whatever
};

this 的值在初始化之前或之后都没有改变。该语言不提供在初始化 block 中引用“正在构造”对象的方法。

关于javascript - typescript : fat arrow & this scope relation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50726554/

相关文章:

javascript - 使用 jQuery 更改背景时,链接会丢失其 css background-color 悬停属性

c# - JavaScript Object.create 和 IE8

typescript - 在带有 Typescript 的 es6 Map 中使用泛型

javascript - 将 PHP 应用程序编译为具有变体的 HTML

javascript - HTML javascript 从输入中获取值

typescript - 如何使 Visual Studio Code 停止显示 node_modules 文件夹的 typescript 错误?

reactjs - 如何在 React 和 typescript 中的样式属性中定义 css 变量

typescript - 受歧视工会在可选属性(property)上受到歧视

javascript - 嵌套订阅并需要所有值作为正文传递给 API - Angular 6 RxJS

javascript - 使用另一个对象的键从对象数组创建新数组