【问题标题】:What is the difference between writing this code with and without class?写这段代码有和没有类有什么区别?
【发布时间】:2022-06-16 00:50:57
【问题描述】:

所以我一直对这个特定问题感到困惑,希望有经验的人可以帮助我解决这个问题。

为什么会这样:

class Set {
  constructor () {
    this.set = {}
  }
  
  add (value) {
    return this.set[value] = true
  }
}

这会将值添加为键,并将键的值添加为 true。所以如果你说这样的话

const mySet = new Set()
mySet.add("hello")

它将返回:{hello: true}

但如果我在 ES6 类之外做这样的事情,那就更像这样:

const car = {
  color: "red"
}

car[built] = 2019

这会说built is undefined,这只能在 ES6 类中使用吗?

【问题讨论】:

  • 试试car["built"] = 2019;

标签: javascript es6-class


【解决方案1】:

car[built] = 2019built 是一个变量

改成car["built"] = 2019

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2017-01-09
    • 2012-09-22
    相关资源
    最近更新 更多