Nevo Mashiach
Nevo Mashiach

Reputation: 135

React functions outside a component

What is the difference between declaring a function outside and inside a component in react?the 'foo' function in the picture

Upvotes: 1

Views: 1742

Answers (1)

Erik Hermansen
Erik Hermansen

Reputation: 2359

The differences aren't really specific to React. Think of the declaration of the function inside of the component as the same as declaration of a function inside of an ordinary JS class.

And with that in mind, the differences are:

  • foo() declared in Game will be a member of any new instance of Game, and can be addressed like Game.foo(). This has implications for it being exposed outside of the module if you export the Game component. If you want foo() to be private for better encapsulation, it might be preferable to declare it outside of Game.

  • If foo() is declared in Game, it somewhat implies that it may have access to other members of Game. You must still bind(this) on the foo() to do that. So in truth, foo() declared in Game doesn't have better access to Game members than foo() declared outside. (You could bind(this) either of them.) But it's a convention that implies access--consider for readability and keeping things straight.

No doubt I forgot something, but I think that's about it.

Upvotes: 2

Related Questions