修饰器是一个函数,用来修改类的行为(扩展类的功能)

  1. {
  2. let readonly = function (target, name, descriptor) {
  3. descriptor.writable = false;
  4. return descriptor;
  5. };
  6. class Test {
  7. @readonly
  8. time() {
  9. return "2020-04-06";
  10. }
  11. }
  12. let test = new Test();
  13. // test.time = function () {
  14. // console.log("reset time");
  15. // };
  16. console.log(test.time()); // 2020-04-06
  17. }
  18. {
  19. let typename = function (target, name, descriptor) {
  20. target.myname = "hello";
  21. };
  22. @typename
  23. class Test {}
  24. console.log("类修饰符", Test.myname); // 类修饰符 hello
  25. // 第三方库修饰器的js库:core-decorators; npm install core-decorators
  26. }
  27. {
  28. // 实现埋点业务逻辑拆分
  29. // 埋点接口 逻辑
  30. let log = (type) => {
  31. return function (target, name, descriptor) {
  32. let src_method = descriptor.value;
  33. descriptor.value = (...arg) => {
  34. src_method.apply(target, arg);
  35. console.info(`log ${type}`);
  36. };
  37. };
  38. };
  39. // 广告方法逻辑
  40. class AD {
  41. @log("show")
  42. show() {
  43. console.info("ad is show");
  44. }
  45. @log("click")
  46. click() {
  47. console.info("ad is click");
  48. }
  49. }
  50. let ad = new AD();
  51. ad.show();
  52. // ad is show
  53. // log show
  54. ad.click();
  55. // ad is click
  56. // log cick
  57. }