decorators

by bingqichen

Babel + JSX

'use strict';

function XMan (target) {
  // target.isXMan = true; // 添加静态属性
  target.prototype.isXMan = true; // 添加实例属性
}

function mix(...args) {
	return function (target) {
  	Object.assign(target.prototype, ...args);
  }
}

const Foo = {
	foo() { console.log('foo', this); },
  type: 'func',
  foo2: () => { console.log(this); }
}

function readonly(target, name, descriptor) {
	descriptor.writable = false;
  console.log(descriptor);
  return descriptor;
}

function deprecate(target, name, descriptor){
    console.warn("[Function " + name + "] has been deprecated.");
    return descriptor;
}

@XMan
@mix(Foo)
class Man {
  constructor(def = 2, atk = 3, hp = 3) {
    this.def = def; // 防御值
    this.atk = atk;  // 攻击力
    this.hp = hp;  // 血量
  }
  
  toString() {
    console.log(`防御力:${this.def},攻击力:${this.atk},血量:${this.hp}`);
  }
  
  @readonly
  w() { return ( `11111`) }
  
  @deprecate
  old_method() {
    console.log("I\"m deprecated"); 
  }
}

const aXMan = new Man(5, 5, 5);
aXMan.w = '11111';
// aXMan.old_method();
// aXMan.foo2();