es7的decorators网上说法是参考了python的decorators。不过我只会java,只能和java的注解做比较。个人感觉是:比java的注解简单,且功能强大。
下面是我用到的常用的一些core-decorators,后面的几个没有写注释,以后补充:
import {
autobind,//方法绑定到实例上(原来是在__proto__里)|可以写在方法或类上(发现写类上后会和readonly等decorators冲突)
readonly,//属性只读|用过发现,这个暂时不支持
deprecate,//使用后调用此方法时会在console中打印过时的相关信息
mixin,//有点相当于jquery的extends可传入多个参数,合并属性到目标__proto__和实例中
time,//console.time使用后打印方法的运行时间
nonconfigurable,
extendDescriptor,
debounce,//设置后方法调用时,数据延时发射,如果多次操作,只处理最后一次的数据,用于防止多次提交|参考underscore.js
throttle,//throttle准时间隔运行,禁用第一次首先执行的话,传递{leading: false}|参考underscore.js
suppressWarnings,//弹出提示信息
enumerable,//可被枚举查询
nonenumerable,//不可被枚举查询
nonconfigurable,//不可被删除
decorate,
lazyInitialize,
} from "core-decorators";
function dec(id){
console.log('evaluated', id);
return (target, property, descriptor) => console.log('executed', id);
}
const SingerMixin = {
sing(sound) {
console.log(sound);
}
};
class Base {
@nonconfigurable
get foo() {
return `hello ${this._foo}`;
}
}
//方法绑定到实例上|可以写在方法或实例上
@mixin(SingerMixin)
export default class extends Base{
constructor(x=1, y=2) {
super();
this.content = '';
}
//@readonly//属性只读|这个暂时不支持
say(){
console.log(this.test);
}
@autobind
say1(){
console.log(this.test);
}
@deprecate('We stopped facepalming', { url: 'http://knowyourmeme.com/memes/facepalm' })//过时
getSelf(){
return this;
}
@time('--singMatingCall')//默认为方法名
singMatingCall() {
this.sing('tweet tweet');
}
//@extendDescriptor
//set foo(value) {
// this._foo = value;
// }
@debounce(500)
updateContent(content) {
console.log("发射数据:"+content);
this.content = content;
}
@throttle(500, {leading: false})
updateContent1(content) {
console.log("发射数据1:"+content);
this.content = content;
}
@suppressWarnings
getSelf2(content) {
this.getSelf();
}
}
可以参考core-decorators的github说明和http://www.w3cschool.cn/ecmascript