配置
babel 依赖包
"devDependencies": {"@babel/cli": "^7.11.6","@babel/core": "^7.11.6","@babel/preset-env": "^7.11.5","@babel/plugin-proposal-decorators": "^7.10.5","@babel/plugin-proposal-class-properties": "^7.10.4"}
babel.config
// .babelrc{"presets":["@babel/preset-env"],"plugins": [["@babel/plugin-proposal-decorators", { "legacy": true }],["@babel/plugin-proposal-class-properties", { "loose" : true }]]}
编译文件
"scripts": {"start": "npx babel app.js -o index.js -w"}
类装璜器
新增办法
@flagclass Animal {constructor(name) {this.name = name;}sayHi() {console.log(this.getName()+" say:'hi'")}} function flag(constructor) {constructor.prototype.getName = function(){return this.name}} let monkey = new Animal("monkey");monkey.sayHi();
传参
@flag({specie:"mammal"})class Animal {constructor(name) {this.name = name;}sayHi() {console.log(this.getName()+" say:'hi'")}} function flag(params) {console.log(params);return (constructor)=>{constructor.prototype.getName = function(){return this.name}}}
办法装璜器
@flagclass Animal {constructor(name) {this.name = name;}@beforesayHi() {console.log(this.getName()+" say:'hi'")}} function flag(constructor) {constructor.prototype.getName = function () {return this.name}} function before(target,property,descripot){let oldMthod = descripot.value;descripot.value = function(){console.log("before exect");oldMthod.call(this, ...arguments);}} let monkey = new Animal("monkey");monkey.sayHi();