0

(Notice to moderators : I have read and understood this excellent thread : How does the "this" keyword work? and it is not related to this question)

I didn't found a similar case mixing jQuery and OOP to pass a context to a jQuery callback.

I defined a class named MySlider and a method named registerListeners on it, but I fail to get the reference to the MySlider object from a jQuery callback.

Any idea?

MySlider.prototype.registerListeners = function () {
    var hello = this;
    $('#sl').slider({
        slide: function (event, ui) {
            console.log(event + " " + ui);

            // how to access 'hello' from here ?
        }
    }) ;
};

Thanks in advance.

BluEOS
  • 361
  • 3
  • 9

1 Answers1

2

Just access it! You've created a closure, where a variable defined in an outer function is accessed from an inner function.

A sort of copy of the variable is stored with the function object. If you did var hello = "tricked you!" after you'd defined your function, the value of hello found in your inner function would update to match.

wizzwizz4
  • 5,219
  • 2
  • 25
  • 49