如何使用和应用JavaScript装饰器? [英] How do I use and apply JavaScript decorators?

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

问题描述

我试图理解如何在一个非常简单的代码中使用装饰器,因此我可以将此概念应用于我的较大项目.从Addy Osmani的文章此处的提示中,我创建了一段简单的代码如下.

I am trying to understand how to use decorators in a very simple piece of code, so I can apply this concept to my bigger project. Taking cue from Addy Osmani's article here, I created a simple piece of code as below.

说,我有一个名为 Cat 的类,带有一个 meow()方法,我想用一些日志记录来装饰它,如下所示.

Say, I have a class called Cat, with a meow() method, I want to decorate it with some logging, as below.

class Cat {
  @logger
  meow() { console.log( ' Meeeoow! ') }
};


function logger(target, key, descriptor) {
  console.log("Cat snarling...");
  return descriptor;
}

const cat = new Cat();
cat.meow();

当我尝试对Node.js解释器(版本9.1.0)执行此操作时,出现以下错误.

When I try to execute this against the Node.js interpreter (version 9.1.0), I get the following error.


/Users/ravindranath/projects/decorators/index.js:2   @logger   ^

SyntaxError: Invalid or unexpected token
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:152:10)
    at Module._compile (module.js:605:28)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
    at Function.Module.runMain (module.js:682:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:613:3

所以,我的问题是:

  1. Node.js 9.x是否支持装饰器语法?还是在将来的某个版本中出现?

  1. Does Node.js 9.x support decorator syntax? Or is it coming up in some future version?

我在GitHub上看到了一些基于 express-js 的装饰器,但是我无法弄清楚如何创建自己的装饰器.有人可以提供一个使用Node.js创建自定义装饰器的简单基本示例吗?

I see some express-js based decorators on GitHub, but I am unable to figure out how to create my own decorator. Can someone provide a simple basic example of creating a custom decorator with Node.js?

推荐答案

装饰器不是ECMAScript 2016(又名7)的一部分.当前,装饰器处于第二阶段草案中,该功能在最终确定之前要经历的全部四个阶段中并成为语言的一部分.它们可能会在不久的将来集成到该语言中,但是其功能和特性可能会发生变化.因此,您必须使用Babel这样的编译器,通过安装

Decorators are not part of ECMAScript 2016 (aka 7). Decorators are currently in Stage 2 Draft out of the total 4 stages a feature goes through before being finalized and becoming part of the language. They'll probably be integrated into the language in the near future, but its features and specifics are subject to change. Because of this, you'll have to use a transpiler such as Babel to transform the decorators into code the Node runtime can understand (ECMAScript 2016) by installing the transform-decorators Babel plugin.

关于创建装饰器,您已经完成了.每个装饰器只是一个包装另一个函数的函数,该函数根据用例(在您的情况下为 target key descriptor )提供了参数..您的 logger 函数:

As for creating decorators, you've already done so. Each decorator is just a function that wraps another, that is provided with arguments based on the usecase, in your case target, key, and descriptor. Your logger function:

function logger(target, key, descriptor) {
  console.log("Cat snarling...");
  return descriptor;
}

已经是一个装饰器.对于类属性和方法 target 指的是属性的类, key 是属性的名称,而 descriptor 是属性的描述符.然后调用装饰器,并通过 Object.defineProperty 一次解散.您的示例可以归结为:

Is already a decorator. For class properties and methods, target refers to the class of the property, key is the property name, and descriptor is the descriptor of the property. The decorator is then called and the property of the class is defined via Object.defineProperty once desugared. Your example can be boiled down to this:

class Cat { }

let meowDescriptor = {
  type: 'method',
  initializer: () => () => {
    console.log(' Meeeoow! ');
  },
  enumerable: false,
  configurable: true,
  writable: true
}

function logger(target, key, descriptor) {
  console.log("Cat snarling...");
  return descriptor;
}

meowDescriptor = logger(Cat.prototype, 'meow', meowDescriptor);
Object.defineProperty(Cat.prototype, 'meow', {
  ...meowDescriptor,
  value: meowDescriptor.initializer()
});

对于类本身,装饰器采用一个参数,即 target ,它描述了装饰的类.我建议阅读一些文档以了解该主题.

For classes themselves, decorators take one argument, target which describes the decorated class. I suggest reading some documentation on the subject to become acquainted with it.

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

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