在修改bug时,无意间看到前同事写的这么一段代码

    1. class ComponentA extends React.Component {
    2. constructor() {
    3. super();
    4. this.handleSubmit = resourcePersimission(this.handleSubmit);
    5. }
    6. @autobind
    7. handleSubmit(permisionModel, model) {
    8. ...
    9. }
    10. render() {
    11. return (
    12. <Form
    13. onSubmit={(model) => this.handleFormSubmit(permissionModel, model)}
    14. ...
    15. />
    16. );
    17. }
    18. }
    19. // 权限校验
    20. function resourcePersimission(fn) {
    21. return function(permisionModel, model) {
    22. ....
    23. };
    24. }

    在构造函数中,调用了一个高阶函数,将 handleSubmit 方法传入其中,并将返回的函数赋值给this.handleSubmit,然后这段代码我的困惑就来了,表单提交的时候,到底是调用的哪个方法呢?是类中定义的,还是高阶函数返回的?
    困惑之余我再次去了解了下 class 这个语法糖,找到了这么一句有用的内容 类的所有方法都定义在类的 prototype 上面。
    于是进行试验一番,果然是这样。
    然后我到babel官网将测试代码转译了下,更加肯定了类的所有方法都定义在类的 prototype 上面的正确性。

    image.png

    所以,答案很明显是会调用构造函数中的 handleFormSubmit 方法。当然为了提高代码的可读性,认为最好还是别用一样的方法名更好。