了解闭包和范围



出于某种原因(可能是因为我不理解闭包(,函数inResult总是返回false并且循环永远不会执行。当然,我确信result包含具有正确的属性。

    function hasId() {return $(this).prop('id');}
    function inResult(res) { return res.hasOwnProperty($(this).prop('id'));}
    $.ajax({
        url : opt.url,
        data : $.extend(true, opt.data, {ids: ids}),
        context : this, // A collection of elements
        type : 'POST',
        dataType : 'json',
        success : function(result) {
            // Filter elements with id and with a property in result named "id"
            this.filter(hasId).filter(inResult(result)).each(function() {
                console.log($(this).prop('id'));
            });
        }
    });

编辑:工作代码解决方案(感谢Šime Vidas让我朝着正确的方向前进(:

// Use closures to change the context later
var hasId    = function() { return $(this).prop('id'); };
var inResult = function(res) { return res.hasOwnProperty($(this).prop('id')); };
$.ajax({
    url : opt.url,
    data : $.extend(true, opt.data, {ids: ids}),
    context : this, // A collection of elements
    type : 'POST',
    dataType : 'json',
    success : function(result) {
        // Filter elements with id and with a property in result named "id"
        var filtered = this.filter(function() {
            // Note the context switch and result parameter passing
            return hasId.call(this) && isBinded.call(this, result);
        });
        filtered.each(function() { console.log($(this).prop('id')); });
    }
});

试试这个:

this.filter( hasId ).filter( function () {
    return inResult( result );
}).each( function () {
    console.log( this.id );
});

在您的代码中,您有.filter(inResult(result))不起作用,因为您要立即调用inResult并将该调用的结果(布尔值(传递给 filter() ,这不适用于布尔值。


你也可以这样做:

var keys = Object.keys( result );
var filtered = this.filter( function () {
    return this.id && keys.indexOf( this.id ) > -1;
});

Object.keys( result )result 返回一个包含所有自己的属性名称的数组。