1

Opposed to my expectation I can't access my class field myLibrary in the class method initialize().

class ViewController {
      myLibrary = new Library();
      initialize() {
        console.log(myLibrary); // undefined

The only "solution" I found was to declare myLibrary outside of the class as a global variable. Is there a way to declare fields in a class and then, well, use them?

4
  • 1
    this.myLibrary…? Commented Mar 28, 2022 at 9:46
  • Side note: If this really is a View controller, then it would be a singleton. In that case, do you really need the class? Can't you just create it as an object with properties and methods? Commented Mar 28, 2022 at 9:48
  • You may want to read the documentation, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - while the example about field declarations is not the brightest one, it already shows that even in the constructor you would need to use this to access member variables. Commented Mar 28, 2022 at 10:15
  • @deceze this may or may not refer to the instance of ViewController that OP has initialized. This depends on the context in which it is called. Commented Oct 19, 2022 at 21:12

2 Answers 2

1

JavaScript classes do not work the same way as Java classes.

To access properties on an object you need to state the object and then access a property on it. They aren't treated as variables in the current scope.

Inside a method, the keyword this will give you the associated object. (See How does the "this" keyword work? for a less simplified explanation).

So you need this.myLibrary instead of just myLibrary.

Sign up to request clarification or add additional context in comments.

Comments

1
class Library {
  …
}

class ViewController {
  constructor() {
    this.myLibrary = new Library();
  }

  log() {
    console.log(this.myLibrary);
  }
}

const viewController = new ViewController();
viewController.log()

2 Comments

Is there any difference between declaring public properties outside and inside the constructor?
Yes, it is a matter of scoping. Who has access to the property/variable and also who can modify it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.