0

I am not understanding why certain functions need the "= () =>" and other functions like 'onFirstDateRendered' don't have "= () =>" what's the difference between these 2 functions within a class based construct? thanks

onGridReady = (params) => {
    this.gridApi = params.api
    this.columnApi = params.columnApi
    this.gridApi.sizeColumnsToFit()
}

onFirstDataRendered(params) {
    params.api.sizeColumnsToFit()
}  
1

1 Answer 1

5

I'm guessing these are both within a class construct. The first is a property declaration using an arrow function. The second is a method definition.

Sometimes people use the property-with-arrow-function form so that regardless of how the function is called, this during the call will be the instance of the class that the property was created on; often these are event handlers. In constrast, with method definitions, the value of this during the method call depends on the way the method is called.

Sign up to request clarification or add additional context in comments.

6 Comments

React discourages inheritance with components, so the prototype shouldn't be a problem. When testing a component, it shouldn't be needed to mock an event handler on the component itself. Mocking normally happens within the props, and if there's an edge case where it's needed to mock, it's still not impossible with somthing like Jest's spyOn.
FWIW, there's an argument for not using property declarations with arrow functions to address ensuring this: They don't end up on the prototype, which makes various things a bit challenging (you can't mock the methods of the class when they're done that way, for instance). You can still use method syntax if you bind in the constructor (this.onGridReady = this.onGridReady.bind(this);) or use a binding decorator (if you're using decorators). More on that in this Medium article.
@EmileBergeron - Yeah, and that parenthetical didn't really belong in the answer anyway. :-) Converted it to a comment. Subclassing and testing aren't the only reasons for having methods on prototypes, though. But either way...
For clarification what is the purpose of this.onGridReady.bind(this)? what is the 'bind' doing?
the link definitely helped. thanks for the responses
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.