为什么在 `this == null` 时不触发 TypeError

Why not trigger the TypeError when `this == null`

Array.prototype._find = function(callbackfn, thisArg) {
  if (this == null) {
    throw new TypeError('this is null or not defined')
  }
  if (typeof callbackfn !== 'function') {
    throw new TypeError('callbackfn is not a function')
  }

  for (let i in this) {
    if (callbackfn.call(thisArg, this[i], i, this)) return this[i]
  }

  return undefined
}

console.log(Array.prototype._find.call(null, x => x > 21))

这是一个 Array.prototype.find polyfill,我除了在 运行 console.log(Array.prototype._find.call(null, x => x > 21)) 时触发 TypeError,我很困惑为什么不触发 TypeError

您可能 运行 您的函数处于 "non-strict" 模式。根据文档:

function.call(thisArg, arg1, arg2, ...)

thisArg

Optional. The value of this provided for the call to a function. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode, null and undefined will be replaced with the global object and primitive values will be converted to objects.

From the MDN page on Function.prototype.call,强调我的

这是一个例子。第一个块以严格模式运行,并将记录 null。第二个将记录 window,因为这是您浏览器的全局范围。 (请给堆栈片段一些时间来记录 window 对象,它很慢)

(function() {
  "use strict";
  
  function logThis() { console.log("strict:", this); }
  
  logThis.call(null);

}());

(function() {
  
  function logThis() { console.log("non-strict:", this); }
  
  logThis.call(null);

}());