如何在字符串原型扩展方法中使用字符串方法

How do I use a string method inside a string prototype extension method

本文关键字:字符串 方法 原型 扩展      更新时间:2023-09-26

我有以下javascript方法:

String.prototype.includesAny = function(search) {
  var found = false;
  search.forEach(function(str) {
    if(this.toLowerCase().includes(str.toLowerCase())) {
      found = true;
    }
  });
  return found;
};

但是会抛出错误:

this.toLowerCase不是函数

我认为这是因为this在这一点上实际上不是String的实例?有人知道做我正在做的事情的正确方法吗(并且仍然使用原型范例)?

在javascript this是函数作用域,所以创建一个新的函数创建一个新的this

您的forEach调用有一个回调,这是一个函数,并且在该函数中this不再是字符串,而很可能是窗口

解决方案是简单地在外部函数

中存储对this的引用。
String.prototype.includesAny = function(search) {
    var found = false,
        input = this;
    search.forEach(function(str) {
        if (input.toLowerCase().includes(str.toLowerCase())) {
            found = true;
        }
    });
    return found;
};

Array.forEach也有一个可选的thisArg,可以使用

String.prototype.includesAny = function(search) {
    var found = false;
    search.forEach(function(str) {
        if (this.toLowerCase().includes(str.toLowerCase())) {
            found = true;
        }
    }, this);
    return found;
};

或者更好,使用Array.some

String.prototype.includesAny = function(search) {
    return search.some(function(str) {
        return this.toLowerCase().includes(str.toLowerCase());
    }, this);
};

作为旁注,扩展本地原型通常是一个坏主意。

你可能是正确的关于this不是一个字符串,因为你在foreach。因此,在进入foreach之前,将this的实例存储在一个变量中,并使用它。

var stringToCheck = this;
search.forEach(function...

您需要将this保存在其他变量中以便在其他函数范围中使用。