Just getting started with ES6 classes. As far as I understood it, this was supposed to behave predictably inside a class and always point to the object. However, that doesn’t seem to be the case:
class BodyPixController {
#target; //Declare a private property
constructor(target){
this.#target = target; // Set the property
console.log(this); // logs: BodyPixController {#target: 'photo'}
addEventListener('load', this.init); // Calls the method
}
init() {
console.log(this); // logs: Window {window: Window, self: Window, document: document, name: '', location: Location,…}
const img = document.getElementById(this.#target); // Throws error: Cannot read private member #target from an object whose class did not declare it
console.log(img);
async function loadAndPredict() {
const net = await bodyPix.load( /** optional arguments, see below **/ );
const segmentation = await net.segmentPerson(img);
console.log(segmentation);
}
loadAndPredict();
}
}
In the code above, this only points to the instantiated object inside the constructor. As soon as the init() method is called, this points to Window. Why? And how do I access private properties from inside methods?