Kevin Powell - CommunityKP-C
Kevin Powell - Community16mo ago
23 replies
snxxwyy

class questions

Hey, i have a few questions about classes given this code:
class Message {
  constructor(message) {
    this._message = message
  }
 
  get message() {
    return this._message
  }
}

x = new Message("example message")
console.log(x.message)

1) why does the this variable need to have a different identifer (in this case _) to prevent it from giving this error? "Uncaught TypeError: Cannot set property message of #<Example> which has only a getter at new Example"

2) if i try to use a function that isn't a getter to return a this value, like below, it returns "ƒ getMessage() { return this._message; }" rather than "example message". Why is this? Is there anything like this with setters too?
class Message {
  constructor(message) {
    this._message = message
  }
 
  getMessage() {
    return this._message
  }
}

3) why may you want to store a class in a variable? e.g. const x = class Message {...}

Thanks in advance.
Was this page helpful?