0
    Array.prototype.forEach = function(callback, context) {
        for (var i = 0; i < this.length; i++) {
            callback.call(context || null, this[i], i, this);
        }
    };

    ["a", "b", "c"].forEach(function(value, index, array) {
        assert(value,
                "Is in position " + index + " out of " +
                        (array.length - 1));
    });

I don't fully understand why null is used here. I guess when I use the invoke foreach, if I miss the context parameter, it will replace it with null? Will callback.call(context || null, this[i], i, this) execute? Can someone explain this for me?

4

2 回答 2

1

如果您为 'context' 传递一个虚假值,(context || null)将导致 null。JS 会将 null 作为第一个参数传递给callback.call(). 第一个参数是this回调函数。

于 2013-08-07T02:25:47.640 回答
1

它实际上不应该在那里。undefined并且在作为参数null传递给时具有相同的效果(函数的参数设置为)。thisFunction.prototype.callthisundefined

于 2013-08-07T02:33:24.380 回答