javascript - 为什么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 上提出的另一个问题有关。
解决方案
的值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);
推荐阅读
- c++ - 大数的 std::bad_array_new_length
- ios - 我的 Xamarin.ios BLE 示例“如何在 iOS 上与低功耗蓝牙设备通信”崩溃
- angular - 无法在打字稿中设置未定义的属性(已定义)
- python-3.x - Python Pydantic 双基模型
- scala - Scala:路径相关类型上的模式匹配
- php - Vue CLI+Laravel Api 请求/响应 400 错误请求
- visual-studio-code - ctrl-e 在 Visual Studio 代码中的两个文件之间切换
- php - 在“支付订单”页面 Woocommerce 上保存账单和运输字段数据
- kotlin - KOTLIN:如何为函数中的泛型类型参数分配默认值?
- octave - 增量搜索方法脚本错误