简体   繁体   English

如何在香草Javascript(ES6)中模拟AngularJs装饰器的工作?

[英]How to emulate what AngularJs decorators are doing in vanilla Javascript (ES6)?

AngularJs Decorators Provides an effective way to extend functions in services without affecting the original service. AngularJs装饰器提供了一种有效的方式来扩展服务中的功能而不影响原始服务。 How does one emulate this behavior with javascript classes? 如何用javascript类模仿这种行为?

I have 2 libraries. 我有2个图书馆。 One containing common logic and UI elements and another more specific to the page I am building. 一个包含常见的逻辑和UI元素,另一个包含特定于我正在构建的页面的元素。 I have to extend the class written in the library containing the core logic in my specific one and then use the extended version's functions from the core library. 我必须扩展写在包含特定核心逻辑的库中的类,然后使用核心库中扩展版本的功能。 I do understand this might seem like a faulty design, but the same could be achieved with decorators in AngularJS.However, I am using plain ES6 Classes. 我确实理解这似乎是一个错误的设计,但是使用AngularJS中的装饰器也可以实现同样的效果,但是我使用的是普通的ES6类。 So how do I go about it? 那我该怎么办呢?

Rather silly example: 有点愚蠢的例子:

class A {foo() {console.log(1)}}
var a  = new A();
// super decorate
var t  = a.foo; a.foo = () => { console.log(2); t()}
// awesome result:
a.foo()
>> 2
>> 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM