【问题标题】:Access variable in function of same object [duplicate]同一对象的函数中的访问变量[重复]
【发布时间】:2018-02-07 18:01:43
【问题描述】:
{
    title: "This is title of item 1",
    desc: "This is description of 1",
    state: "inactive",
    toggleState: () => {
        console.log('title: ', title)
    }
}

这是 Typescript 中的一个对象。我想在这个对象的函数 toggleState() 中访问这个对象的 title 变量。但我得到错误

[ts]:找不到名称“标题”

有可能吗?如果是,那么如何实现呢?

【问题讨论】:

  • Please don't mark duplicate without giving proper solution! 这不是它的工作原理,如果它是重复的,那是因为重复已经有了答案:p
  • 重复意味着确实有解决方案。 :(
  • @no1xsyzy 它确实有解决方案!
  • @ArnoldParge 看这句话,does have been != does have

标签: javascript json function typescript object


【解决方案1】:

这行得通吗?

var obj = {
  title: "This is title of item 1",
  desc: "This is description of 1",
  state: "inactive",
  toggleState: function() {
    console.log('title: ', this.title)
  }
}.toggleState();

【讨论】:

  • 对之前的评论表示歉意。没想到你从箭头函数变成了普通函数
猜你喜欢
  • 2021-09-09
  • 2020-06-16
  • 2019-12-05
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 2016-07-15
相关资源
最近更新 更多