使用“invert”扩展 Javascript 中的布尔对象功能
我想用一个原型函数来扩展布尔对象,该函数可以反转它的当前值。到目前为止,我一直在做这样的事情:
var bool = true;
bool = !bool;
console.log(bool); // false
我扩展布尔对象的尝试没有取得成果。这就是我所取得的进展:
Boolean.prototype.invert = function() {
return !this.valueOf();
}
var bool = true;
bool = bool.invert();
console.log(bool); // false
接近,但还不够接近。我正在寻找以下解决方案:
var bool = true;
bool.invert();
console.log(bool); // false
是的,我知道,扩展内置对象通常被认为是一个坏主意。请让我们改天再讨论。
I would like to extend the Boolean object with a prototype function that inverts it's current value. Until now, I've been doing something like this:
var bool = true;
bool = !bool;
console.log(bool); // false
My attempts at extending the Boolean object were not fruitful. That's how far I got:
Boolean.prototype.invert = function() {
return !this.valueOf();
}
var bool = true;
bool = bool.invert();
console.log(bool); // false
Close, but not close enough. I am looking for a solution along these lines:
var bool = true;
bool.invert();
console.log(bool); // false
Yes, I know, extending build-in Object is commonly considered a bad idea. Please let's save that discussion for another day.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
标量值在所有 oop 语言中都是不可变的,您需要一个新类
,但这不太聪明,您可以将布尔值存储在一个对象中并将该对象作为引用传递
Scalar values are immutable in all oop languages, you need a new class
but this is not so smart, you can store the boolean-value in one object and pass this object as reference