通过ES7装饰器获取方法参数

时间:2018-12-31 17:27:55

标签: javascript reactjs decorator ecmascript-next

我正在尝试使用ES7装饰器,并编写了一个方法装饰器,该装饰器仅记录调用方法的参数。

它与this.sum(6, 5)类似,works in some cases,但不适用于 箭头函数this.arrowSum(5, 10)和默认参数this.sum()

我是否缺少某些东西,或者仅仅是当前装饰器实现中的一个限制?

import React from "react";
import ReactDOM from "react-dom";

function logArgs() {
  return function(target, property, descriptor) {
    let originalMethod = descriptor.value;
    descriptor.value = function(...args) {
      console.log(...args);
      return originalMethod.call(this, ...args);
    };

    return descriptor;
  };
}

class App extends React.Component {
  @logArgs()
  sum(a = 1, b = 2) {
    return a * b;
  }

  @logArgs()
  arrowSum = (a = 3, b = 4) => {
    return a * b;
  };

  render() {
    return (
      <div>
        {this.sum()} <br /> {this.sum(6, 5)}
        <br />
        {this.arrowSum()} <br /> {this.arrowSum(5, 10)}
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

0 个答案:

没有答案