MDN String.prototype.repeat polyfill-'this'的值如何为null?

问题描述 投票:1回答:3

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

这怎么可能为空?

javascript polyfills
3个回答
1
投票

喜欢这个:

String.prototype.repeat.call()

1
投票

您可以使用callapply在其他上下文中执行功能。大多数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

0
投票
const test = 'test'.repeat;
test();
© www.soinside.com 2019 - 2024. All rights reserved.