【问题标题】:How do I use a string method inside a string prototype extension method如何在字符串原型扩展方法中使用字符串方法
【发布时间】:2016-11-02 19:10:23
【问题描述】:

我有以下 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 prototype-programming


【解决方案1】:

在 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);
};

顺便说一句,扩展原生原型通常是个坏主意。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      您需要将this 保存在其他变量中才能在其他函数范围内使用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-17
        • 1970-01-01
        • 1970-01-01
        • 2017-03-26
        • 2011-07-09
        • 2014-03-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多