【问题标题】:JavaScript decorators example not workingJavaScript 装饰器示例不起作用
【发布时间】:2016-03-28 06:59:55
【问题描述】:

我正在尝试学习 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"
    ]
  }
}

【问题讨论】:

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

标签: javascript object decorator babeljs


【解决方案1】:

谢谢@torazaburo,这行得通。

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

@superhero
class MySuperHero {

}

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      • 2020-11-09
      • 2015-09-03
      • 2016-07-25
      相关资源
      最近更新 更多