Skip to content

Latest commit

 

History

History
42 lines (32 loc) · 820 Bytes

装饰器.md

File metadata and controls

42 lines (32 loc) · 820 Bytes

返回目录

JavaScript 装饰器学习与实战

在编写 JavaScript 代码时我们往往需要

function timeout(milliseconds = 0) {
  return function(target, key, descriptor) {
    var originalMethod = descriptor.value;

    descriptor.value = function(...args) {
      setTimeout(() => {
        originalMethod.apply(this, args);
      }, milliseconds);
    };

    return descriptor;
  };
}

class DemoComponent {
  constructor() {}

  @timeout()
  demoMethod() {
    // This code will run at the next tick...
    console.log("0 ms Later");
  }

  // With a number
  @timeout(2000)
  demoMethod() {
    // This code will run at the next tick...
    console.log("2000 ms Later");
  }
}

new DemoComponent().demoMethod();

console.log("Main Process...");