在变量 returns 内调用的函数未定义

Function called inside an variable returns undefined

我正在尝试从一个函数中获取输出,在调用它时应该 return John temp (2021) 但我得到的是 John undefined (undefined)

const user = {
    username : 'John',
    type: 'temp',
    yearJoin: 2021,
    userString(){
        function getUserDetails (){
            return `${this.type} (${this.yearJoin})`
        }
        return `${this.username} ${getUserDetails()}`;
    }
}
console.log(user.userString())

您需要将 getUserDetails 调用的范围设置为 this:

getUserDetails.call(this)

参见:

const user = {
  username: 'John',
  type: 'temp',
  yearJoin: 2021,
  userString() {
    function getUserDetails() {
      return `${this.type} (${this.yearJoin})`
    }
    return `${this.username} ${getUserDetails.call(this)}`;
  }
}

console.log(user.userString());

您可以通过将 getUserDetails 函数作为对象的方法向上移动来清理它:

const user = {
  username: 'John',
  type: 'temp',
  yearJoin: 2021,
  getUserDetails() {
    return `${this.type} (${this.yearJoin})`
  },
  toString() {
    return `${this.username} ${this.getUserDetails()}`;
  }
}

console.log(user.toString());

现在更进一步,作为 class,您有:

class User {
  constructor({ username, type, yearJoin }) {
    this.username = username;
    this.type = type;
    this.yearJoin = yearJoin;
  }
  getUserDetails() {
    return `${this.type} (${this.yearJoin})`
  }
  toString() {
    return `${this.username} ${this.getUserDetails()}`;
  }
}

const user = new User({
  username: 'John',
  type: 'temp',
  yearJoin: 2021
});

console.log(user.toString());