[ES7] Exploring ES2016 Decorators
Original artial --> link
How descorator looks like:
@mydecorator
function myFun(){
...
}
Descorator in action:
We have a class, which have an method call meow():
class Cat { meow(){ console.log(`Meow!!`); } }
When Javascritp Engine read it, it looks like:
Object.defineProperty(Cat.prototype, 'meow', { value: specifiedFunction, enumerable: false, configurable: true, writable: true, })
Imagine we want to mark a property or method name as not being writable. A decorator precedes the syntax that defines a property. We could thus define a`@readonly` decorator for it as follows:
function readonly(target, key, descriptor){ descriptor.writable = false; return descriptor; }
and add it to our meow property as follows:
class Cat { @readonly meow() { return `say meow!` } }
Now, before installing the descriptor onto `Cat.prototype`, the engine first invokes the decorator:
Then if you have mark 'writable' to 'false' by adding @readonly descortaor, if we trying to overwrite the 'meow' method, it will report error.
Check out libaray, it has many pre-defined descorators: npm, Github
Decorate a class:
function superhero(isSuperhero ){ return function(target){ return class{ isSuperhero = isSuperhero } } } @superhero(true) class MySuperHero{ isSuperhero = null; constructor(){} } const hero = new MySuperHero(); console.log(hero.isSuperhero); //true
Continue reading:
- https://github.com/wycats/javascript-decorators
- https://github.com/jayphelps/core-decorators.js
- http://blog.developsuperpowers.com/eli5-ecmascript-7-decorators/
- http://elmasse.github.io/js/decorators-bindings-es7.html
- http://raganwald.com/2015/06/26/decorators-in-es7.html
- Jay’s function expression ES2016 Decorators example
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具