0

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!

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
jhonatanoliveira
  • 141
  • 1
  • 11
  • When you set up the event handler, instead of just passing `object.toggleBackgroundTools` as the function pass an anonymous function wrapped around a call to the function via the object reference. JavaScript objects don't work the same was as in other languages. – Pointy Nov 30 '14 at 23:23
  • 1
    Try `this.backgroundButton.mouseClicked(this.toggleBackgroundTools.bind(this))`. – Luke B. Nov 30 '14 at 23:23
  • It did it, @LukeB.! I didn't know the method *bind*. (I'm new in OOP for javascript, coming from Java). Thanks a lot! Also, thanks, @Pointy. I'll try your way too. – jhonatanoliveira Nov 30 '14 at 23:43
  • 1
    @jhow basically `.bind()` is a function that does what I described: it gives you a function that guarantees that the *real* function you want to call is called so that `this` has the right value. – Pointy Nov 30 '14 at 23:56

0 Answers0