1

My question relates to an implementation detail in the redux-form source code. Simply, I'd like some insight into the reasoning behind and thinking that went into the following snippet of code that can be found in src/createField.js here and here.

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

My question is not about how or where these functions are being used, but specifically why are these functions are wrapped in the manner that they are. For instance why not simply use:

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

My guess is that it has to do with storing direct references to these functions in a parent component. My interest in this is related to another question I've asked on SO.

Stuart Bourhill
  • 603
  • 4
  • 10

1 Answers1

0

The value of this depends on how a function is called. Separating a function call from the object will break the connection to that object in 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);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Interesting observation - perhaps I'm not entirely convinced by your example: the function is wrapped like so `() => nextProps.validate` not `() => nextProps.validate()` so when the value is [unwrapped](https://github.com/erikras/redux-form/blob/23b1fbd219bd1d81b55e2271c3352379c70007c4/src/createReduxForm.js#L658) and finally [used](https://github.com/erikras/redux-form/blob/23b1fbd219bd1d81b55e2271c3352379c70007c4/src/generateValidator.js#L18) the lexical scope of `this` as it was is not kept. Or am I missing something? – Stuart Bourhill May 31 '18 at 11:36
  • Note that `validate` can be a function or an array of functions or undefined if no value is passed in. – Stuart Bourhill May 31 '18 at 11:39
  • @StuartBourhill —`() => nextProps.validate` creates a function which **mentions** `nextProps.validate` but doesn't call it and effectively does nothing at all. – Quentin May 31 '18 at 22:07