我今天如何使用装饰器? [英] How can I use decorators today?

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

问题描述

我看到装饰器今天已经在一些javascript代码中使用了。我的问题实际上是双重的。

I see decorators being used today already in some javascript code. My question is really two fold.

首先:

如果装饰者还没有最终确定怎么可能今天在生产代码中使用它们?浏览器支持不会不存在吗?

If decorators have not even been finalized how is it possible to use them in production code, today? Won't browser support be non-existent?

第二:

鉴于今天可以使用它,正如一些开源项目所暗示的那样,通常建议让装饰器工作的设置是什么?

Given it is possible to use it today, as some open source projects would suggest, what's a typically recommended setup for getting decorators to work?

推荐答案

你是对的, ES2016装饰器尚未成为规范的一部分。但这并不意味着我们今天不能使用它。

You're right, ES2016 decorators are not yet part of the spec. But it doesn't mean we can't use it today.

首先让我们退后一步,看看什么是装饰者。装饰器只是为对象添加行为的包装器。它不是javascript中的新概念(或者一般的编程),它实际上已经存在了一段时间......

First let's take a step back and go over "what is a decorator". Decorators are simply wrappers that add behavior to an object. It's not a new concept in javascript (or programming in general), it's actually been around for a while...

这是一个检查权限的装饰器的基本示例:

Here's a basic example of a decorator that checks permissions:

function AuthorizationDecorator(protectedFunction) {
    return function() {
        if (user.isTrusted()) {
            protectedFunction();
        } else {
            console.log('Hey! No cheating!');
        }
    }
}

使用它看起来像这样:

AuthorizationDecorator(save);

你看到我们所做的只是简单地结束其他一些功能。你甚至可以通过多个装饰器传递一个函数,每个装饰器都添加一些功能或运行一些代码。

You see all we're doing is simply wrapping up some other function. You can even pass a function through multiple decorators each adding a piece of functionality or running some code.

你甚至可以找到一些旧文章解释javascript中的装饰模式。

You can even find some old articles explaining the decorator pattern in javascript.

现在我们了解装饰器实际上是我们的东西(javascript)社区)总是能够做到的,当我们今天使用ES2016装饰器时,它们可能只是简单地被编译成ES5代码,因此为什么你保持浏览器兼容性。因此暂时它只是语法糖(我可能会添加一些非常甜的糖)。

Now that we understand decorators are actually something we (javascript community) were always able to do, it probably comes as no shock that really when we utilize ES2016 decorators today they are simply just being compiled down to ES5 code hence why you maintain browser compatibility. So for the time being it is simply syntactic sugar (some really sweet sugar I might add).

至于用于将ES2016代码转换为ES5代码的编译器,你有一些选择: Babel Traceur 是最受欢迎的。

As for which compiler to use to convert your ES2016 code to ES5 code, you have some choices: Babel and Traceur are the most popular.

以下是探索ES2016装饰器

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

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