这在对象内部的模板文字中

this in template literals inside objects

提问人:MARCUS ANTENOR 提问时间:6/14/2023 更新时间:6/14/2023 访问量:7

问:

const me = {
  fName: "Marc",
  mName: "Fenzy",
  lName: "Antenor",
  friends: ["Julbert", "Gracia", "Ralph", "Mackendy", "Roselaure", "Wilny"],
  randFriend: function(){
    let friendIndex = Math.floor(Math.random() * (this.friends.length));
    
    return `Name of a good friend of mine? It's ${this.friends[friendIndex]}.`;
  },
  family: {
    dad: "Jesmane",
    mom: "Raymonde",
    brother: ["Kenley", "Dave", "Sammy"],
  },
  birthYear: 1992,
  calcAge: function () {
    this.age = 2023 - this.birthYear;
    return this.age;
  },
  myState: 'miami',
  zipCode: 33169,
  address: `1140 nw 155th ln, apt 105, ${this.State}, ${this.zipCode}.`,
  // address: function(){
  //   return `1140 nw 155th ln, apt 105, ${this.myState}, ${this.zipCode}.`;
  // },
};

const location = me.address;
console.log(location);

// const location = me.address();
// console.log(location);

我花了 30 分钟才意识到这一点。每次打印位置时,myState 和邮政编码都会返回 undefined。同时,在前面的示例中,我使用模板文字,它工作正常。然后我意识到它们之间的共同点是它们位于函数内部。 当我在函数中设置地址时(如图所示),它打印得很好。我认为这与这个属性有关,但不能把我的头包裹起来。有人可以帮忙解释一下吗?

反对 这个 字符串文字

评论


答: 暂无答案