Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

91
Views
Access Javascript class fields in class methods

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

class Library {
  …
}

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

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

const viewController = new ViewController();
viewController.log()
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!