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?
CodePudding user response:
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
.
CodePudding user response:
class Library {
…
}
class ViewController {
constructor() {
this.myLibrary = new Library();
}
log() {
console.log(this.myLibrary);
}
}
const viewController = new ViewController();
viewController.log()
CodePudding user response:
Use this
to access properties of your object.
class ViewController {
constructor(){
this.myLibrary = new Library();
}
initialize() {
console.log(this.myLibrary); //
}
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Getter
get firstNameAndLastName() {
return this.calcFullName();
}
// Method
calcFullName() {
return `${this.firstName} ${this.lastName}`;
}
}