关于jquery在一个类中的范围

lax*_*j11 1 javascript jquery scope jquery-plugins

我希望能够通过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();
Run Code Online (Sandbox Code Playgroud)

aar*_*ing 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();
Run Code Online (Sandbox Code Playgroud)