为什么在Array.prototype.forEach()中检查null?

时间:2016-03-01 03:32:04

标签: javascript arrays foreach

MDN polyfill for Array.prototype.forEach()

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {

  Array.prototype.forEach = function(callback, thisArg) {

    var T, k;

    if (this == null) {
      throw new TypeError(' this is null or not defined');
    }

    // 1. Let O be the result of calling toObject() passing the
    // |this| value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get() internal
    // method of O with the argument "length".
    // 3. Let len be toUint32(lenValue).
    var len = O.length >>> 0;

我无法想象this == null会发生的情况。能给我举个例子?感谢。

1 个答案:

答案 0 :(得分:4)

因为您可以使用call() / apply() / bind()

在javascript中传递this的自定义值
[].forEach.call(null, function(){})