Using jQuery in object method defined via MyObject.prototype.method and the 'this' variable [duplicate]

StackOverflow https://stackoverflow.com/questions/22671732

문제

I'm currently diving into Object-oriented programming in JavaScript and I came across a problem. I'm defining an object like below, doing some jQuery stuff inside one of the methods, and I'm wondering what is the best way to access Object properties inside a jQuery method that overrides the 'this' variable.

function MyObject() {
    this.foo = 'bar';
}

MyObject.prototype.myMethod = function () {
    $.get('myurl', function (data) {
        // how to address this.foo here ?
    });
};
도움이 되었습니까?

해결책

Save a reference to this before calling $.get.

MyObject.prototype.myMethod = function () {
    var that = this;
    $.get('myurl', function (data) {
        console.log(that.foo);
    });
};

다른 팁

Just create a variable in the scope of the outer function to preserve its context:

MyObject.prototype.myMethod = function () {
    var self;
    self = this;
    $.get('myurl', function (data) {
        // how to address this.foo here ?
        self.doStuff();
    });
};

For callbacks, you may want to make use of jQuery.proxy, which is jQuery's souped-up version of Function.prototype.bind:

function MyObject(selector) {
    this.foo = 'bar';
    $(selector).on('click', $.proxy(this, 'myMethod'));
}
MyObject.prototype.myMethod = function (e) {
    console.log(this.foo); //'bar'
};

For your case specifically, you can make use of jQuery.proxy to generate a callback for the $.get success function:

MyObject.prototype.myMethod = function () {
    $.get('myurl', $.proxy(this, 'myCallback'));
};
MyObject.prototype.myCallback = function (data) {
    console.log(this.foo); //'bar'
};

Alternatively, you can write the proxy inline:

MyObject.prototype.myMethod = function () {
    $.get('myurl', $.proxy(function (data) {
        console.log(this.foo); //'bar'
    }, this));
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top