javascript代码中的null? Array.prototype.forEach=函数(回调,上下文){ for(var i=0;i

javascript代码中的null? Array.prototype.forEach=函数(回调,上下文){ for(var i=0;i,javascript,Javascript,我不完全理解为什么这里使用null。我猜当我使用invokeforeach时,如果我错过了context参数,它将替换为null?调用(上下文| | null,this[i],i,this)执行吗?有人能给我解释一下吗?如果您为“context”传递一个错误的值,(context | null)将导致null。JS将null作为第一个参数传递到callback.call()中。第一个参数是回调函数的this。它实际上不应该在那里undefined和null与this参数传递给Function.p

我不完全理解为什么这里使用
null
。我猜当我使用invoke
foreach
时,如果我错过了
context
参数,它将替换为
null
?调用(上下文| | null,this[i],i,this)执行吗?有人能给我解释一下吗?

如果您为“context”传递一个错误的值,
(context | null)
将导致null。JS将null作为第一个参数传递到
callback.call()
中。第一个参数是回调函数的
this

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

因此,即使我将null或undefined传递给Function.prototype.call,Function.prototype.call仍然可以执行?@joesmith:this参数可以接受任何值。在非严格模式下,如果将
null
undefined
作为
this
参数传递,则函数中的
this
将是
undefined
    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));
    });