我目前有一个叫isColor的String.protype,它是检查颜色的,但我不想让它在函数里有一个参数。
我想把这样的东西存档。
const color = 'red';
console.log(color.isColor());
预期输出:true
在方法内部,比较 this
(实例)与你要比较的任何东西进行对比。
String.prototype.isColor = function() {
return ['red', 'orange', 'yellow'].includes(String(this));
}
console.log('red'.isColor());
console.log('somethingElse'.isColor());
你需要 String
转换成 this
如果你在草率的模式下运行脚本,在这种情况下就会出现 this
将是一串 对象,而不是一串 原始的,所以你需要在比较之前把它变成一个基元。
但请记住,突变内置原型是 很 陋习 - 如果可能的话,你应该强烈考虑使用不同的方法。