I am coding a javascript program using a nice library called p5. I am trying to OOP in javascript, but I am having a problem with the scope of the pointer this. Inside the constructor of my BackgroungTools class I define some class' members, as shown below:
BackgroundTools = function() {
this.isBackgroundToolsOn = false
this.backgroundButton = createButton('Background')
this.backgroundButton.position(20,20)
this.backgroundButton.mouseClicked(this.toggleBackgroundTools)
this.backgroundSliderRed = createSlider(0,255)
this.backgroundSliderRed.position(20,50)
this.backgroundSliderRed.hide()
console.log(this)
}
BackgroundTools.prototype.toggleBackgroundTools = function() {
console.log(this)
if (this.isBackgroundToolsOn) {
this.backgroundSliderRed.hide()
this.isBackgroundToolsOn = false
} else {
this.backgroundSliderRed.show()
this.isBackgroundToolsOn = true
}
}
Notice that mouseClicked, in the constructor, receives a method from the class as argument, it's a callback function. Later, I then instantiate this class inside the setup function of p5:
function setup() {
canvas = createCanvas(800,600)
background(0)
backgroundTools = new BackgroundTools()
}
function draw() {
}
When this is printed in the Constructor we get what is expected (a pointer to the current object). But when I click in the button and the method toggleBackgroundTools is called, the this inside it isn't what we expect to be: it isn't a pointer to the current object, but it's something that prints in the console this: [top: Window[0], window: Window[0], location: Location, external: Object, chrome: Object…]
I think that the method mouseClicked from p5.Element sort of change the scope of this. But I want to access the class' members in toggleBackgroundTools method.
Someone has went through this before? Any ideas on how can I deal with this situation?
Thanks a lot!