es6装饰器

配置

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"

}

类装饰器

新增方法


@flag

class 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

}

}

}

方法装饰器


@flag

class Animal {

constructor(name) {

this.name = name;

}

@before

sayHi() {

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();

你可能感兴趣的:(es6)