I have these two questions concerning JS. I must say I've really done my research but couldn't find anything about them.
The questions are:
- Why can't
console.log
and variable identifiers(var
,let
,const
) be used inside a class, outside of functions/methods?
E.g.(pseudo code):
class App extends Component {
console.log(this) <--* ['Unexpected keyword or identifier']
let a = 1 <--* ['Unexpected token']
state = { <--* [variable without identifier is alright]
characters: [
{
name: 'Charlie',
job: 'Janitor'
}, etc...
}
removeCharacter = (index) => {
console.log(this) <--* [works here normally]
const characters = this.state.characters
etc...
})
})
...
}
- Why does a function needs another function to be called? I mean, in what situations does it become necessary? This comes from something like:
const TableBody = (props) => {
const rows = props.characterData.map((row, index) => {
return (
<tr key={index}>
<td>{row.name}</td>
<td>{row.job}</td>
[this] *--> <button onClick={() => props.removeCharacter(index)}>Delete</button>
</tr>
)
[instead of something like] *--> <button onClick={props.removeCharacter(index)}>Delete</button>
I mean, props.removeCharacter(index)
is itself a call already, isn't it?
Thank you!
CodePudding user response:
You can do
class TheClass {
theProperty = 'theValue'
as part of class field syntax, which is syntax sugar for
class TheClass {
constructor() {
this.theProperty = 'theValue'
It's only for assigning properties to the instance, and nothing else.
console.log(this)
doesn't work because it doesn't make sense there - it's not assigning a property, it's just a floating expression.
let a = 1
doesn't work because you can't declare a new variable there - the {
of a class doesn't create a new block. Using class fields assigns to properties of the instance, and doesn't create new standalone identifiers.
Why does a function needs another function to be called?
In this situation, it's needed because you need to pass an argument. If removeCharacter
didn't accept an argument, you could do
<button onClick={props.removeCharacter}>
But it does accept an argument, which is expected to be the index. But the default argument that gets passed to a click handler is the event.
You can't do
onClick={props.removeCharacter(index)}
because that would invoke removeCharacter
immediately. It'd be equivalent to
const result = props.removeCharacter(index);
// ...
<button onClick={result}
which isn't the logic that's needed - you want removeCharacter
to be called when the button is clicked, not when the button is created.