如何在字符串原型扩展方法中使用字符串方法
How do I use a string method inside a string prototype extension method
我有以下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
保存在其他变量中以便在其他函数范围中使用。
相关文章:
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- 在JavaScript中拆分日期字符串的更好方法是什么
- 用Javascript重新格式化复杂文本日期字符串的更好方法
- 用javascript修复这个JSON对象字符串最干净的方法是什么
- jQuery字符串使用split()方法在空格后拆分字符串
- 使用查询字符串方法清除浏览器缓存
- 使用子字符串方法时应用程序挂起的原因
- 使用字符串方法更改Javascript对象中的DOM元素参数
- 在Javascript中对对象属性执行字符串方法
- 直接访问字符串方法
- 尝试我自己的字符串方法来删除元音
- 对字符串方法的ajax调用不起作用
- 字符串方法精确文本
- 如何在字符串原型扩展方法中使用字符串方法
- 有没有任何字符串方法,能让我把一串数字,转换成一串数字和字母
- 字符串方法
- 在定义新的字符串方法时使用reduce()
- 问题与自定义大写字符串方法,jQuery和Select2
- 使用比较字符串方法或使用==验证密码字段,但两者都不起作用
- 如何防止javascript缓存?查询字符串方法不起作用