name : function(){} or function name (){} | ReactJS
name : function(){} or function name (){} | ReactJS
I am new to ReactJS and as I am learning I noticed that there's a few ways to declare functions such as,
MyFunc : function(){
///
}
or
function MyFunc(){
///
}
I was wondering which one shall i use and why?
The first one is a syntax error, the second isn't ?!
– Jonas W.
Jun 29 at 11:08
It's not a react specific
– The Reason
Jun 29 at 11:08
@the reason react is the new jquery ;)
– Jonas W.
Jun 29 at 11:10
2 Answers
2
This is not a React specific way of declaring functions. It is a javascript way.
MyFunc : function(){
///
}
Would be in an object literal and
function MyFunc(){
///
}
Would be a constructor or general function.
For example
const someObject = {
MyFunc: function() {
// some definition here.
}
}
and
function MyFunc {
// some definition here. Something like this.name = 'blah'
}
Which one shall I use and why
That would depend on what behavior you would like. With the constructor function notation, you create an object that can be instantiated into multiple instances (with the new
keyword), while the literal notation delivers a single object, like a singleton
.
new
singleton
Thank you for a detailed answer.
– Muhib Al Hasan
Jun 29 at 12:16
Go with
function MyFunc(){
///
}
For more details see refernce: https://reactjs.org/docs/faq-functions.html
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Those two are not interchangeable the way you posted them. In context where first works the second won't, and vice versa.
– dfsq
Jun 29 at 11:08