我正在学习OOP javascript ...在我的示例代码中,我无法从ajax方法中访问属性和方法...为什么,这样做的正确方法是什么? http://jsbin.com/votajaxo/1/

var Person = function(name){
    this.name = name;
};

Person.prototype = {
    doAjax: doAjax,
    changeName: changeName
};

function doAjax(url){
    console.log(this.name); // John

    $.ajax({
        url: url,
        beforeSend: function(xhr){
            console.log(this.name); // undefined
            console.log(typeof this.changeName); // undefined
            xhr.abort();
        }
    });
}

function changeName(newName){
    this.name = newName;
}

var p = new Person('John');
p.doAjax('/handler');

===============>>#1 票数:3

您必须明确设置将在其中调用闭包的上下文。 jQuery通过context: $.ajax()选项提供此功能:

$.ajax({
    url: url,
    context: this, // <-- add this
    beforeSend: function(xhr){
        console.log(this.name);
        console.log(typeof this.changeName);
        xhr.abort();
    }
});

===============>>#2 票数:2 已采纳

您将需要使用闭包来保留对对象“ this”的引用:

var Person = function(name){
    this.name = name;
};

Person.prototype = {
    doAjax: doAjax,
    changeName: changeName
};

function doAjax(url){
    var context = this;
    console.log(this.name); // John

    $.ajax({
        url: url,
        beforeSend: function(xhr){
            console.log(context.name); // John
            console.log(typeof context.changeName); 
            xhr.abort();
        }
    });
}

function changeName(newName){
    this.name = newName;
}

var p = new Person('John');
p.doAjax('/handler');

===============>>#3 票数:0

您还可以bind所需的上下文bind到回调..以便在执行时获得正确的上下文。

function doAjax(url){
    console.log(this.name); // John

    $.ajax({
        url: url,
        beforeSend: function(xhr){
            console.log(this.name); // undefined
            console.log(typeof this.changeName); // undefined
            xhr.abort();
        }.bind(this) // <-- binds call to current context.
    });
}

http://www.smashingmagazine.com/2014/01/23/understanding-javascript-function-prototype-bind/

  ask by spikes translate from so

未解决问题?本站智能推荐: