什么是“装饰器"?它们是如何使用的? [英] What are "decorators" and how are they used?

查看:30
本文介绍了什么是“装饰器"?它们是如何使用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇 AngularJS 中的装饰器到底是什么.除了 AngularJS 文档 以及 youtube 视频中的简短(尽管很有趣)提及.

I'm curious what exactly decorators are in AngularJS. There isn't much information online for decorators save for a blurb in the AngularJS documentation and a brief (albeit interesting) mention in a youtube video.

正如 Angular 的人所说,装饰器是:

As the Angular guys put it a decorator is:

服务的装饰,允许装饰者拦截服务实例创建.返回的实例可能是原始实例,或委托给原始实例的新实例.

Decoration of service, allows the decorator to intercept the service instance creation. The returned instance may be the original instance, or a new instance which delegates to the original instance.

我真的不知道那意味着什么,而且我不确定您为什么要将此逻辑与服务本身分开.例如,如果我想在不同的条件下返回不同的东西,我只需将不同的参数传递给相关函数或使用另一个共享该私有状态的函数.

I don't really know what that means, and I'm not sure why you would separate this logic from the service itself. For example if I wanted to return something different under different conditions I would just pass different arguments to the relevant functions or use another function sharing that private state.

我仍然是一个 AngularJS 菜鸟,所以我确定这只是我的无知和/或坏习惯.

I'm still kind of an AngularJS noob so I'm sure it's just ignorance and/or bad habits I've picked up.

推荐答案

$provide.decorator 的一个很好的用例是当你需要对某些第三方/上游做一些小的调整"服务,您的模块所依赖的服务,同时保持服务完好无损(因为您不是服务的所有者/维护者).这里是关于 plunkr 的演示.

A good use case of $provide.decorator is when you need to do minor "tweak" on some third-party/upstream service, on which your module depends, while leaving the service intact (because you are not the owner/maintainer of the service). Here is a demonstration on plunkr.

这篇关于什么是“装饰器"?它们是如何使用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆