JavaScript 装饰器示例不起作用

JavaScript decorators example not working

我正在尝试学习 javascript 中的装饰器。我正在尝试为本教程 here 获取一个小示例 运行。这会记录 undefined,我不确定为什么。

function superhero(target) {
  target.isSuperhero = true
  target.power = 'flight'
}

@superhero
class MySuperHero { }

let superman = new MySuperHero()

console.log(superman.power) // should log flight

当我这样做时,我得到了错误 You have trailing decorators with no method

class MySuperHero {
  @superhero
}

这是我的 package.json

{
  "devDependencies": {
    "babel-cli": "^6.3.17",
    "babel-core": "^6.3.21",
    "babel-plugin-syntax-decorators": "^6.3.13",
    "babel-plugin-transform-decorators": "^6.3.13",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.3.13"
  },
  "babel": {
    "presets": [
      "es2015"
    ],
    "plugins": [
      "syntax-decorators",
      "transform-decorators-legacy"
    ]
  }
}

谢谢@torazaburo,这有效。

function superhero(target) {
  target.isSuperhero = true
  target.power = 'flight'
}

@superhero
class MySuperHero {

}

console.log(MySuperHero.power) // "flight"

修饰值不会出现在实例上。尝试记录 MySuperHero.isSuperhero.