javascript - 理解闭包和作用域

标签 javascript jquery closures

出于某种原因(可能是因为我不理解闭包)函数 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 并传递 result 该调用(这是一个 bool 值)到 filter(),它不适用于 bool 值。


你也可以这样做:

var keys = Object.keys( result );

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

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

关于javascript - 理解闭包和作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9035841/

相关文章:

c# - 是否需要引用变量才能将它们包含在闭包中?

Swift 闭包类型转换

javascript - React 大日历页面

javascript - 从数据库存储和检索时 FullCalendar 日期不同

javascript - 使用 jQuery 的网格大小调整器

javascript - 在 symfony2 中使用 assetic 进行源映射

javascript - 在 Angularjs 中按对象属性过滤

javascript - 向多个设备发送推送 FCM (Web) 无法生成通知 key

javascript - 使用 JQuery 延迟加载 div,代码在 Chrome 中不起作用(window.onload)

groovy - 为什么在 Groovy shell 中运行闭包递归示例时会收到 "No signature of method""错误?