Reputation: 37
Consider the example:
<input type="text" onChange={this.name} />
In this example name
function does not contain the braces, why? And when I put braces, it will rise the error. I want to know the reason behind this error.
Upvotes: 2
Views: 1026
Reputation: 1306
In JavaScript, functions are values. It means it can be used on any expression context, like passing values to functions or be returned from functions. A function's value is it own name. Not to be confused with the return value of the function.
Parentheses is a JavaScript operator used to create function call expressions, between other use cases.
In your case, you are passing the value this.name
for the property onChange
of the React's input
element. The onChange
expects a function value
to be called in response to a change event. This way, React itself will call the function using the parentheses operator to that end, in this context.
If, otherwise, you've written this.name()
, you're already making a function call, which will result in a error, since you're bypassing React expected behavior.
Upvotes: 0
Reputation: 33
In JavaScript, a function is an object, much like other objects.
You can assign a function to a variable.
let foo = function () {
return "bar"
}
And later you can add the parentheses to that variable name to call the function.
foo() // Returns "bar".
You can pass the variable around like any other variable, for example as a parameter to another function.
function baz (some_function) {
return some_function()
}
baz(foo) // Returns "bar".
This is what happens in your example. this.name
gets passed to the function that handles the onChange
event, and at some point inside that function, it adds the parentheses to evaluate the function you passed.
That is why, if you add the parentheses when you pass the function, then the function gets evaluated, and the result is passed:
baz(foo()) // Uncaught TypeError: some_function is not a function
Here, foo()
has already been evaluated, and the variable some_function
in baz
contains the string "bar"
instead of a function.
Upvotes: 3
Reputation: 31625
Function "without braces" is a pointer to some function.
Here is an example.
let bananas = function(){ console.log('bananas') }
When you do this, you don't call the function, only references it, only create a pointer to the function.
With that reference, you can call bananas()
any time you want, not only when the code is read.
The reason why you pass only the reference of a function in react is that inside the component, some where, it will call the function.
If you just make this <input type="text" onChange={this.name()} />
, at the time you are rendering the input, name()
is called, but if you only pass the reference to the function, react will only call the function when the event (onChange) happen.
Upvotes: 0