【问题标题】:Why not trigger the TypeError when `this == null`为什么在 `this == null` 时不触发 TypeError
【发布时间】:2018-09-26 05:09:34
【问题描述】:
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

【问题讨论】:

    标签: javascript arrays find polyfills


    【解决方案1】:

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

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

    thisArg

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

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

    这是一个例子。第一个块在严格模式下运行并将记录null。第二个将记录window,因为这是您浏览器的全局范围。 (请给栈 sn-p 一些时间来记录窗口对象,这很慢)

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

    【讨论】:

      猜你喜欢
      • 2018-06-25
      • 2010-11-18
      • 2012-08-23
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多