Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OO JavaScript - Avoiding self = this

Tags:

javascript

Does anyone know of a way to get around declaring var self = this when using JavaScript in an OO fashion? I see it quite often and was curious if its just something you have to do, or if there really is a way (perhaps a class library?) that lets you get around it? I do realize why it is necessary (this has function scope). But you never know what clever ways may be out there..

For example, I usually code my "classes" like this in JS:

function MyClass() {

}

MyClass.prototype = {

    firstFunction: function() {

        var self = this;

        $.ajax({
            ...
            success: function() {
                self.someFunctionCall();

            }
        });
    },

    secondFunction: function() {

        var self = this;

        window.setTimeout(function() {
            self.someOtherFunction();
        }, 1000);
    }

};
like image 684
Brian DiCasa Avatar asked Jul 25 '12 01:07

Brian DiCasa


1 Answers

In your first function you can do this...

$.ajax({
    context: this,
    success: function() {
        this.someFunctionCall();

    }
});

In the second one, you can do this, though you'll need to shim .bind() in older browsers...

window.setTimeout(function() {
    this.someOtherFunction();
}.bind(this), 1000);

With jQuery, you could also do this...

window.setTimeout($.proxy(function() {
    this.someOtherFunction();
}, this), 1000);
like image 160
2 revs, 2 users 93%user1106925 Avatar answered Sep 17 '22 20:09

2 revs, 2 users 93%user1106925