关于jquery在一个类中的范围

时间:2011-02-24 23:45:37

标签: javascript jquery jquery-plugins scope

我希望能够通过ajax ...

调用info ['id']
var setEditor = function()
{
    this.info = {
        'id' : 1    // <--------------- i want this
    };

    var cardEditor = function()
    {
        var status = {
            'touched' : false,
            'id' : 0
        };
        card.children('input').bind('focusout', function() {
            alert(this.info['id']);  // <----------------- through this
            $.ajax({
                type : 'POST',
                url : '../addcard',
                data : 'name=John&location=Boston',
                dataType : 'json',
                success: function(msg){
                    $('#rec').html(msg);
                }
            });
        });

    };
};

set = new setEditor();

1 个答案:

答案 0 :(得分:5)

问题是this是一个在不同时间引用不同内容的关键字。诀窍是通过在that 引用您想要的内容时为其分配this来创建新变量this。然后通过词法作用域可以访问嵌套函数。我通常在构造函数的顶部做一次。

var setEditor = function()
{
    var that = this;  // that is not a keyword and will always refer this as it is
                      // interpreted at the line of assignment (until that itself is
                      // redefined of course). this will mean something
                      // else when run in an event handler.

    this.info = {
        'id' : 1    // <--------------- i want this
    };

    var cardEditor = function()
    {
        var status = {
            'touched' : false,
            'id' : 0
        };
        card.children('input').bind('focusout', function() {
            alert(that.info['id']);  // now refers to the object and not the input
                                     // element.
            $.ajax({
                type : 'POST',
                url : '../addcard',
                data : 'name=John&location=Boston',
                dataType : 'json',
                success: function(msg){
                    $('#rec').html(msg);
                }
            });
        });

    };
};

set = new setEditor();