这个/ bind的JS Prototype范围

时间:2011-11-28 18:06:11

标签: javascript jquery bind this

我有以下代码在JavaScript中创建一个对象。它使用prototype来定义函数和构造函数。

function objectClass(){
    this.variables = new Array();
}

objectClass.prototype = 
{
    contructor: objectClass,

    setInfo: function(){
        $.ajax({
            url: "info.json",
            success: function(){
                //for each json element returned...
                this.variables.push(json[i]);
            }
        });
    }
    getInfo: function(){
        return this.variables;
    },
}

这是我想要做的类似的例子。我需要能够在调用obj.getInfo()时返回变量数组。它总是抛出一个错误。我相信这是因为"这个"指的是ajax成功函数的范围。

关于如何让它引用对象变量的任何想法?

1 个答案:

答案 0 :(得分:4)

这是正确的,this值不会自动传递,因此不会设置为实例。要强制执行此操作,您可以使用context接受的$.ajax属性:

$.ajax({
    context: this, // `this` is the instance here

这会将成功回调中的this值设置为您指定的值。