Javascript: Static - undefined

Viewed 75

i try with the static method to define more than one variables, but got still the following Error:

Cannot read properties of undefined (reading 'navbar')

export default class Dropdown {
    static options = {
        navbar: '.main-navbar'
    }
    init () {
        this._navbar = document.querySelector(this.options.navbar);
    }
}
1 Answers

When calling a static variables from a class, instead of using this, you need to use the class name

// This will fail
class ClassName {
  static varName = 'Static'
  constructor() { console.log('Static: ' + this.varName) }
}
new ClassName()

// This will work
class ClassName {
  static varName = 'Static'
  constructor() { console.log('Static: ' + ClassName.varName) }
}
new ClassName()

Related