(I am using google translator)
class User{
name="tom"
showName(){
console.log(this.name)
}
}
const tom = new User()
console.log(tom.name)
The code above prints Tom . But if I change the second line like this, I get an error.
var name="Tom"
let name="Tom"
const name="Tom"
this.name="Tom"
The way class field syntax was designed, such a line can do one thing: it assigns to a property of the instance.
this.name = "tom" isn't syntactically permitted because it would have been redundant.
var name = and other variants aren't permitted in that position because those are variable declaration keywords (var, let, const) - which keyword you use has various implications on the scope of the newly created variable, and whether it can be reassigned. But this makes no sense in the context of a class field, because you aren't creating a new identifier, you're assigning to a property of an object.
This
class User{
name="tom"
is the same as doing
class User{
constructor() {
this.name = "tom";
}
name is not a new variable created in a particular scope - it's only a property, so using var, let, or const when declaring it would mix two entirely separate concepts, and so is forbidden.
So, you can only do
class User{
name="tom"
(Unless you want the property to be private (only useable from the inside of the class), in which case prefix the property name with a #.)
class User{
#name="tom"
I think what you wanted in your question is to know another way to declare variables in a js class. So, you can use a constructor to achieve that, something like that:
class User{
constructor() {
this.name = "tom"
}
showName(){
console.log(this.name)
}
}
const tom = new User()
console.log(tom.name)
That’ll print "tom" as well.