如何从其方法中的函数访问对象的属性?

时间:2014-04-21 03:42:11

标签: javascript jquery

我正在学习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');

3 个答案:

答案 0 :(得分: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();
    }
});

答案 1 :(得分: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');

答案 2 :(得分:0)

您还可以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/