为什么当this == null时不触发TypeError

时间:2018-09-26 05:09:35

标签: javascript arrays find polyfills

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

1 个答案:

答案 0 :(得分:1)

您可能正在“非严格”模式下运行函数。根据文档:

  

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

     

thisArg

     

可选。此值提供给函数调用。请注意,这可能不是该方法看到的实际值:如果该方法是非严格模式下的函数,则nullundefined将被全局对象替换,原始值将转换为对象。

From the MDN page on Function.prototype.call,重点是

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

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

}());

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

}());