当前位置: 首页 > 工具软件 > speak.js > 使用案例 >

es6 core-decorators.js

赵英哲
2023-12-01

core-decorators.js

core-decorators.js是一个第三方模块,提供了几个常见的修饰器,通过它可以更好地理解修饰器。

(1)@autobind

ES6 autobind修饰器使得方法中的this对象,绑定原始对象。

  1. import { autobind } from 'core-decorators';
  2. class Person {
  3. @autobind
  4. getPerson() {
  5. return this;
  6. }
  7. }
  8. let person = new Person();
  9. let getPerson = person.getPerson;
  10. getPerson() === person;
  11. // true

(2)@readonly

readonly修饰器使得属性或方法不可写。

  1. import { readonly } from 'core-decorators';
  2. class Meal {
  3. @readonly
  4. entree = 'steak';
  5. }
  6. var dinner = new Meal();
  7. dinner.entree = 'salmon';
  8. // Cannot assign to read only property 'entree' of [object Object]

(3)@override

override修饰器检查子类的方法,是否正确覆盖了父类的同名方法,如果不正确会报错。

  1. import { override } from 'core-decorators';
  2. class Parent {
  3. speak(first, second) {}
  4. }
  5. class Child extends Parent {
  6. @override
  7. speak() {}
  8. // SyntaxError: Child#speak() does not properly override Parent#speak(first, second)
  9. }
  10. // or
  11. class Child extends Parent {
  12. @override
  13. speaks() {}
  14. // SyntaxError: No descriptor matching Child#speaks() was found on the prototype chain.
  15. //
  16. // Did you mean "speak"?
  17. }

(4)@deprecate (别名@deprecated)

deprecatedeprecated修饰器在控制台显示一条警告,表示该方法将废除。

  1. import { deprecate } from 'core-decorators';
  2. class Person {
  3. @deprecate
  4. facepalm() {}
  5. @deprecate('We stopped facepalming')
  6. facepalmHard() {}
  7. @deprecate('We stopped facepalming', { url: 'http://knowyourmeme.com/memes/facepalm' })
  8. facepalmHarder() {}
  9. }
  10. let person = new Person();
  11. person.facepalm();
  12. // DEPRECATION Person#facepalm: This function will be removed in future versions.
  13. person.facepalmHard();
  14. // DEPRECATION Person#facepalmHard: We stopped facepalming
  15. person.facepalmHarder();
  16. // DEPRECATION Person#facepalmHarder: We stopped facepalming
  17. //
  18. // See http://knowyourmeme.com/memes/facepalm for more details.
  19. //

(5)@suppressWarnings

suppressWarnings修饰器抑制deprecated修饰器导致的console.warn()调用。但是,异步代码发出的调用除外。

  1. import { suppressWarnings } from 'core-decorators';
  2. class Person {
  3. @deprecated
  4. facepalm() {}
  5. @suppressWarnings
  6. facepalmWithoutWarning() {
  7. this.facepalm();
  8. }
  9. }
  10. let person = new Person();
  11. person.facepalmWithoutWarning();
  12. // no warning is logged
 类似资料:

相关阅读

相关文章

相关问答