【问题标题】:Does "this" keyword works with Template literals?“this”关键字是否适用于模板文字?
【发布时间】:2019-10-10 23:16:05
【问题描述】:

我注意到“this”关键字在模板文字中不起作用。是正常还是我的代码有问题?

let dog = {
  name: "Spot",
  numLegs: 4,
  sayLegs: () => `This dog has ${this.numLegs} legs.`
}

输出是“这条狗有未定义的腿。”,只有当我用文字对象名称替换它时它才有效

【问题讨论】:

    标签: this template-literals


    【解决方案1】:

    根据MDN,箭头函数不绑定自己的this

    更多信息也提到here.

    与常规函数不同,箭头函数没有自己的this

    用对象内部的常规函数​​替换箭头函数允许this 引用对象本身。

    let dog = {
        name: "Spot",
        numLegs: 4,
        sayLegs: function () {
            console.log(`This dog has ${this.numLegs} legs.`);
        }
    };
    dog.sayLegs(); // This dog has 4 legs.
    

    在我看来,使用带有闭包或回调函数的箭头函数更可取。 当涉及到类/对象方法或构造函数时,我选择使用常规函数。

    【讨论】:

      猜你喜欢
      • 2013-10-18
      • 2018-03-24
      • 2019-08-06
      • 1970-01-01
      • 2019-02-13
      • 2023-02-03
      • 1970-01-01
      • 2012-03-03
      相关资源
      最近更新 更多