es7 class装饰器
文档http://es6.ruanyifeng.com/#docs/decorator
ts文档 https://www.tslang.cn/docs/handbook/decorators.html#class-decorators
当多个装饰器应用于一个声明上,从上至下调用,从下而上执行
function info(opt: {
username: string;
age: number;
email: string;
}) {
return function (klass: any) {
klass.username = opt.username;
klass.age = opt.age;
klass.email = opt.email;
}
}
@info({
username: 'ajanuw',
age: 14,
email: '123@sina.com'
})
class Ajanuw {
constructor() { }
}
const klass = (<any>Ajanuw);
console.log(klass.username, klass.age, klass.email);
es 的装饰器
let l = console.log
function klass(value) {
return target => {
// l(value) // api
// l(target) // 对象
}
}
function prop(value) {
return function (target, key, des) { // target 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
// l(value) // username
// l(target, key, des) // 对象,属性名,属性描述符
}
}
function func(value) {
return function (target, key, des) { // target 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
// l(value) // function
// l(key) // 函数名 show
// l(des.value) // show函数, 可以改写
// des.value = function(){
// l('hello')
// }
}
}
function Body(target) {
// l( target ) // undefined
}
@klass('api')
class Ajanuw {
@prop('username') name = 'ajanuw'
@func('function')
show(@Body body) {
l(body)
}
}
new Ajanuw().show()
重载构造函数
function classDecorator<T extends { new (...args: any[]): {} }>(
constructor: T
) {
return class extends constructor {
newProperty = "new property";
hello = "override";
};
}
@classDecorator
class Greeter {
constructor(public hello: string) {}
}
var g = new Greeter("world");
console.log(g.hello); // override
参数装饰器
import "reflect-metadata";
const requiredMetadataKey = Symbol("required");
const bodyMetadataKey = Symbol("body");
function required(
target: Object,
propertyKey: string | symbol,
parameterIndex: number
) {
let existingRequiredParameters: number[] =
Reflect.getOwnMetadata(requiredMetadataKey, target, propertyKey) || [];
existingRequiredParameters.push(parameterIndex);
Reflect.defineMetadata(
requiredMetadataKey,
existingRequiredParameters,
target,
propertyKey
);
}
function Body(key: string): any {
return function (target: any, propertyKey: string, parameterIndex: number) {
let existingRequiredParameters: any[] =
Reflect.getOwnMetadata(bodyMetadataKey, target, propertyKey) || [];
existingRequiredParameters.push({ parameterIndex, key });
// 注入元数据
Reflect.defineMetadata(
bodyMetadataKey,
existingRequiredParameters,
target,
propertyKey
);
};
}
function validate(
target: any,
propertyName: string,
descriptor: TypedPropertyDescriptor<any>
) {
let method = descriptor.value;
// 重写value
descriptor.value = function () {
let requiredParameters: number[] = Reflect.getOwnMetadata(
requiredMetadataKey,
target,
propertyName
);
if (requiredParameters) {
for (let parameterIndex of requiredParameters) {
if (
parameterIndex >= arguments.length ||
arguments[parameterIndex] === undefined
) {
throw new Error("Missing required argument.");
}
}
}
// 获取目标对象上提供的元数据键的元数据值
Reflect.getOwnMetadata(bodyMetadataKey, target, propertyName)?.forEach(
(it: any) => {
// 重写参数
arguments[it.parameterIndex] = arguments[it.parameterIndex][it.key];
}
);
return method?.apply(this, arguments);
};
}
class Greeter {
@validate
greet(@required @Body("name") name: any): any {
console.log("Hello " + name); // Hello xxxx
}
}
const g = new Greeter();
g.greet({ name: "xxxx" });
es7 class装饰器的更多相关文章
- 装饰器模式&&ES7 Decorator 装饰器
装饰器模式(Decorator Pattern)允许向一个现有的对象动态添加新的功能,同时又不改变其结构.相比JavaScript中通过鸡肋的继承来给对象增加功能来说,装饰器模式相比生成子类更为灵活. ...
- koa2使用es7 的装饰器decorator
本文主要讲述我在做项目中使用装饰器(decorator)来动态加载koa-router的路由的一个基础架构. 目前JavaScript 对decorator 是不支持,但是可以用babel 来编译 既 ...
- JS 装饰器,一篇就够
更多文章,请在Github blog查看 在 ES6 中增加了对类对象的相关定义和操作(比如 class 和 extends ),这就使得我们在多个不同类之间共享或者扩展一些方法或者行为的时候,变得并 ...
- 简单理解 ES7 Decorator(装饰器)
如何使用ES7 Decorator给你的游戏人物开挂? // 预告: 本文有点小难度,对js不太熟的人可能比较懵逼 // 本文的目的是让你们知其然 // ======================= ...
- 在express中使用ES7装饰器构建路由
在Java的Spring框架中,我们经常会看到类似于@Controller这样的注解,这类代码能够极大的提高我们代码的可读性和复用性.而在Javascript的ES7提案中,有一种新的语法叫做deco ...
- 从C#到TypeScript - 装饰器
总目录 从C#到TypeScript - 类型 从C#到TypeScript - 高级类型 从C#到TypeScript - 变量 从C#到TypeScript - 接口 从C#到TypeScript ...
- Javascript 装饰器极速指南
pablo.png Decorators 是ES7中添加的JavaScript新特性.熟悉Typescript的同学应该更早的接触到这个特性,TypeScript早些时候已经支持Decorators的 ...
- 【Angular专题】 (3)装饰器decorator,一块语法糖
目录 一. Decorator装饰器 二. Typescript中的装饰器 2.1 类装饰器 2.2 方法装饰器 2.3 访问器装饰器 2.4 属性装饰器 2.5 参数装饰器 三. 用ES5代码模拟装 ...
- MobX基础 ----- 类的静态属性和装饰器
当我们使用MobX的时候,首先要声明一个store, 用来保存状态,它的最基本的语法 如下: class Todo { @observable title = ""; @obser ...
随机推荐
- Machine、Swarm、Compose、SocketPlane这些Docker生态圈软件各解决了哪些问题?
Machine:解决的是操作系统异构安装Docker困难的问题,没有Machine的时候,CentOS是一种,Ubuntu又是一种,AWS又是一种.有了Machine,所有的系统都是一样的安装方式. ...
- WIN10平板 总是提示你需要管理员权限怎么办
例如在往C盘拷贝文件的时候,会出现下面的提示,虽然点击继续也可以执行,但是还是非常麻烦 WIN+R,打开组策略 在Windows设置-安全设置-安全选项中,找到用户账户控制,设置为已禁用,应用 ...
- Android中windowTranslucentStatus与windowTranslucentNavigation的一些设置(转)
在iOS中,你可能发现页面会整体拉升到状态栏,整个页面效果就会显得更加的高端大气上档次,在Android4.4以后其实也有这种效果的实现,下面我就说一下在进行这种效果实现时碰到的一些坑,希望对大家有一 ...
- wamp设置实现本机IP或者局域网访问
在 httpd.conf 中查找 Allow from 127.0.0.1 Order Deny,Allow Deny from all Allow from 127.0.0.1 在此下面加上 All ...
- 小白学python时候总会遇到的几个问题
最近又在跟之前的同学一起学习python,一起进步,发现很多测试同学在初学python的时候很容易犯一些错误,特意总结了一下.其实这些错误不仅是在学python时会碰到,在学习其他语言的时候也同样会碰 ...
- linux下无法执行PHP命令,错误 php: command not found
在linux下执行php时无法执行,报错:php: command not found 解决方法: export PATH=$PATH:/usr/local/php7/bin 可以输入echo $PA ...
- Nginx 目录结构
Nginx 目录结构 Nginx 安装后整体的目录结构及文件功能如下: [root@localhost ~]# tree /usr/local/nginx /usr/local/nginx ├── c ...
- WEBAPI 的简单示例
一.webapi 1.在webapiconfig中移除xml的返回格式,返回格式就自动使用Json格式 config.Formatters.Remove(config.Formatters.XmlFo ...
- PHP优化——从语言到业务
经常有人说php速度慢,其实语言层面的速度差异和实际的业务相比,不在一个数量级. 业务的瓶颈往往在于io,而不是CPU. 0x0 语言 语法 单引号和双引号 单引号不解析字符串里的变量,而双引号会解析 ...
- 【iCore4 双核心板_ARM】例程十九:USBD_MSC实验——虚拟U盘
实验步骤: 1.将SD卡插在SD卡槽中. 2.将跳线冒跳至USB_OTG,将USB_OTG通过Micor USB线与USB主机(电脑)相连. 3.烧写程序,我的电脑中将出现一个磁盘. 实验现象: 核心 ...