MDN String.prototype.repeat polyfill - 'this' 怎么可能有空值?

MDN String.prototype.repeat polyfill - How can 'this' have value null?

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');

这怎么可能为空?

像这样:

String.prototype.repeat.call()

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

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

因此,进行了一项简单的检查,以确保没有人尝试在 nullundefined

的上下文中执行它
String.prototype.repeat.call(null, 2); // TypeError
const test = 'test'.repeat;
test();