2015-12-22 98 views
0

我正在嘗試在JavaScript中學習裝飾器。我正在嘗試爲本教程here運行一個小例子。這記錄undefined,我不知道爲什麼。JavaScript裝飾器示例不工作

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" 
    ] 
    } 
} 
+1

裝飾值不會出現在實例上。嘗試記錄'MySuperHero.isSuperhero'。 – 2015-12-22 04:58:58

回答

1

感謝@torazaburo,這個工程。

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

@superhero 
class MySuperHero { 

} 

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

裝飾值不會出現在實例上。嘗試登錄MySuperHero.isSuperhero。