代码之家  ›  专栏  ›  技术社区  ›  Stuart Bourhill

为什么redux表单源代码中的这个函数会被另一个函数包装?

  •  1
  • Stuart Bourhill  · 技术社区  · 8 年前

    我的问题涉及到 redux-form 源代码。简单地说,我想深入了解以下代码片段背后的推理和思考,这些代码可以在 src/createField.js here here .

    this.context._reduxForm.register(
         newName,
         'Field',
         () => nextProps.validate,
         () => nextProps.warn
    )
    

    我的问题是 关于如何或在何处使用这些函数,但具体而言 为什么? 这些函数的包装方式是这样的。例如,为什么不简单地使用:

    this.context._reduxForm.register(
      newName,
      'Field',
      nextProps.validate,
      nextProps.warn
    )
    

    我的猜测是,它与在父组件中存储对这些函数的直接引用有关。我对这件事的兴趣与另一件事有关 question 我已经问过了。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Quentin    8 年前

    价值 this 取决于函数的调用方式。将函数调用与对象分离将断开与该对象的连接 .

    var nextProps = {
        validate: function () { console.log("This is ", this); }
    };
    
    function callFunction(callback) {
        callback();
    }
    
    console.log("======");
    console.log("Preserve this");
    callFunction(() => nextProps.validate());
    console.log("======");
    console.log("Don't preserve this");
    callFunction(nextProps.validate);