参考文档http://greengerong.com/blog/2015/09/23/es7-zhi-decorators-shi-xian-aopshi-li/
注意:依赖babel-preset-stage-2(stage-0和1 不行),和babel-plugin-transform-decorators-legacy
packag脚本
"scripts": {
"build": "babel demo.js -o bundle.js"
},
执行 npm run build,之后执行node build,可以看到效果
demo.js 见下面
.babelrc
{
"presets": [
"es2015",
"stage-2"
],
"plugins": ["transform-decorators-legacy"]
}
demo
var logger = {
info(msg)
{
console.log(msg);
}
}
let log = (type) => {
return (target, name, descriptor) => {
const method = descriptor.value;
descriptor.value = (...args) => {
logger.info(`(${type}) before function execute: ${name}(${args}) = ?`);
let ret;
try {
ret = method.apply(target, args);
logger.info(`(${type})after function execute success: ${name}(${args}) => ${ret}`);
} catch (error) {
logger.error(`(${type}) function execute error: ${name}(${args}) => ${error}`);
} finally {
logger.info(`(${type}) function execute done: ${name}(${args}) => ${ret}`);
}
return ret;
}
}
}
class MyClass {
@log('MyClass add')
add(a, b){
return a + b;
}
}
var NC = new MyClass();
NC.add(1,2)