在此 JavaScript 代码中为 null

null in this code of javascript?

本文关键字:null 代码 JavaScript 在此      更新时间:2023-09-26
    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));
    });

我不完全明白为什么在这里使用null。我想当我使用调用foreach时,如果我错过了context参数,它会用null替换它?callback.call(context || null, this[i], i, this)会执行吗?有人可以为我解释一下吗?

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

如果为

"context"传递一个错误的值,(context || null)将导致 null。JS会将null作为第一个参数传递给callback.call()。第一个参数是回调函数的this