博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[TypeScript] Understanding Decorators
阅读量:6832 次
发布时间:2019-06-26

本文共 1348 字,大约阅读时间需要 4 分钟。

Decorators are a feature of TypeScript that are becoming more and more common in many major libraries. This lesson walks you through what decorators are and how to create your own.

 

Nomarl way to decorate a object :

const Person = {name: 'John'};function addAge(age){    return function(person){        return {            age,            name: person.name        }    }}const john = addAge(30)(Person);console.log(john); // {name: "John", age: 30}

 

In Typescript, we can enable "experimentaDecorators", which is ES7 feature:

{    "compilerOptions": {        "rootDir": "src",        "module": "commonjs",        "target": "es5",        "noImplicitAny": false,        "sourceMap": false,        "outDir": "./dist",        "noEmitOnError": true,        "experimentalDecorators": true    },    "exclude": [        "node_modules",        "typings/main",        "typings/main.d.ts"    ]}

 

function addAge(age){    return function(targetClass){        return class{            age = age;            name = new targetClass().name;        }    }}@addAge(30)class Person{    name = "Johnn";}const john = new Person();console.log(john); // {name: "Johnn", age: 30}

As before we create addAge function as decorator, different from before, it return class, because we want to decorate Person class.

After the decorator, we will have age prop on the person class.

转载地址:http://yajkl.baihongyu.com/

你可能感兴趣的文章
Linux安装mysql 8.0
查看>>
Webpack vs Rollup
查看>>
Springboot 前后端参数交互方式
查看>>
px、em、rem、%、vw、vh、vm等单位有什么区别?
查看>>
滴滴出行基于RocketMQ构建企业级消息队列服务的实践
查看>>
如何理解git rebase?
查看>>
程序部署到服务器服务无法启动问题
查看>>
以太坊源码分析—p2p节点发现与协议运行
查看>>
在MaxCompute上分析IP来源的方法
查看>>
JavaScript对象内部属性及其特性总结
查看>>
python学习笔记(二)
查看>>
css3动画效果抖动解决
查看>>
在React中你可以停止使用这五种常见写法
查看>>
为什么要用Redis
查看>>
SpringMVC学习笔记
查看>>
JDK源码学习1-ThreadPoolExecutor学习,先看注释
查看>>
使用VUE搭建后台管理系统(登陆篇)
查看>>
简单易懂的现代魔法-递归
查看>>
机器学习应用中的UI个性化
查看>>
【大数据实践】Kafka生产者编程(5)——ProducerConfig详解(下)
查看>>