【问题标题】:MDN String.prototype.repeat polyfill - How can 'this' have value null?MDN String.prototype.repeat polyfill - 'this' 怎么会有 null 值?
【发布时间】:2020-02-17 14:13:21
【问题描述】:

在MDN doc for String.prototype.repeat polyfill 中有这行代码:

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null)
      throw new TypeError('can\'t convert ' + this + ' to object');

这怎么可能是空的?

【问题讨论】:

  • 请注意,undefined == null 在使用== 而不是=== 进行检查时也是true

标签: javascript polyfills


【解决方案1】:

您可以使用call 或apply 在另一个上下文中执行函数。大多数 JavaScript 函数都被设计为泛型,也就是说它适用于大多数变量类型。

String.prototype.repeat.call(1, 2); // -> "11"
String.prototype.repeat.call({}, 2); // -> "[object Object][object Object]"

因此,进行了一项简单的检查,以确保没有人尝试在 null 或 undefined 的上下文中执行它

String.prototype.repeat.call(null, 2); // TypeError

【讨论】:

    【解决方案2】:

    像这样:

    String.prototype.repeat.call()
    

    【讨论】:

      【解决方案3】:
      const test = 'test'.repeat;
      test();
      

      【讨论】:

      • 与其他 OO 语言不同,在 Javascript 中,调用代码时的上下文会影响“this”的值。在 Andrey 的回答中,该方法已作为函数被捕获到变量中。调用该函数不再是原始对象的上下文,因此“this”不再是原始对象。
      猜你喜欢
      • 2014-05-26
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多