[英]Get value of string before the prototype
I currently have a String.protype called isColor, which is checking the color.我目前有一个名为 isColor 的 String.protype,它正在检查颜色。 But i dont want it to have an argument inside the function.但我不希望它在 function 中有参数。
I want to archive something like this:我想存档这样的东西:
const color = 'red';
console.log(color.isColor());
expected output: true
预期 output: true
Inside the method, compare the this
(the instance) against whatever you're comparing it against:在方法内部,将this
(实例)与您要与之比较的任何内容进行比较:
String.prototype.isColor = function() { return ['red', 'orange', 'yellow'].includes(String(this)); } console.log('red'.isColor()); console.log('somethingElse'.isColor());
You need the String
to convert the this
if you run the script in sloppy mode, in which case this
will be a string object , not a string primitive , so you need to turn it into a primitive before comparison.如果您在草率模式下运行脚本,则需要String
来转换this
,在这种情况下, this
将是字符串object ,而不是字符串原语,因此您需要在比较之前将其转换为原语。
But keep in mind that mutating built-in prototypes is very bad practice - you should strongly consider using a different approach, if at all possible.但请记住,改变内置原型是非常糟糕的做法- 如果可能的话,您应该强烈考虑使用不同的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.