0

Can I have a class like this?

class Human {
  constructor(name) {
    this.name = name;
  }
  someMethod() {
    this.hasBrain = true;
    console.warn(this.hasBrain);
  }
}

This is working and not throwing any error. My question is, now, is hasBrain a class property or it is a class field? if it is a class field, Does it have to be declared?

  • classes in javascript are built on top of prototypes - so anything you can do in traditional (ES5) prototypes you can do with classes - classes just add some useful syntax and semantics on top of prototypes – Bravo Apr 16 '22 at 00:00
  • `is hasBrain a class property or it is a class field` ... it's a property on the instance – Bravo Apr 16 '22 at 00:09
  • `.hasBrain` is an instance property, just like `.name` is. That the one is created in the constructor and the other in `someMethod` doesn't make a difference (except regarding following best practices). Neither of them is defined using class field syntax. – Bergi Apr 16 '22 at 02:10
  • @Bergi, It is not a duplicate question. hasBrain can be a field which is not declared, but you can get access to it in methods by using this.hasBrain. Please reopen my question, I would like to get more answers on this topic! – RocketJS Apr 16 '22 at 05:35
  • 1
    @RocketJS Wait, is this just a terminology misunderstanding? Are you actually not asking about [class fields](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields), i.e. properties created with special syntax? If so, what do you mean by "*which is not declared*"? – Bergi Apr 16 '22 at 19:56

0 Answers0