首页 > 解决方案 > 为什么redux-form源代码中的这个函数被另一个函数包裹了?

问题描述

我的问题与redux-form源代码中的实现细节有关。简单地说,我想深入了解以下代码片段背后的原因和想法,这些代码片段可以在src/createField.js 此处此处找到。

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

我的问题不是关于这些函数的使用方式或位置,而是具体为什么这些函数以它们的方式包装。例如为什么不简单地使用:

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

我的猜测是它与在父组件中存储对这些函数的直接引用有关。我对此的兴趣与我在 SO 上提出的另一个问题有关。

标签: javascriptreactjsreduxredux-form

解决方案


的值this取决于函数的调用方式。将函数调用与对象分离将断开与该对象的连接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);


推荐阅读