简体   繁体   中英

Passing an object reference to a jQuery callback

(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 registerListener s 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM