使用“invert”扩展 Javascript 中的布尔对象功能

发布于 2024-12-08 23:03:58 字数 514 浏览 0 评论 0原文

我想用一个原型函数来扩展布尔对象,该函数可以反转它的当前值。到目前为止,我一直在做这样的事情:

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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

桃扇骨 2024-12-15 23:03:58

标量值在所有 oop 语言中都是不可变的,您需要一个新类

var BooleanBuilder = function( data ){ this._data = !!data; };

BooleanBuilder.prototype.valueOf = function() {
    return this._data;
};
BooleanBuilder.prototype.invert = function() {
    this._data = !this._data;
};

var bool = new BooleanBuilder(true);
alert(bool.valueOf());
bool.invert();
alert(bool.valueOf());  // false

,但这不太聪明,您可以将布尔值存储在一个对象中并将该对象作为引用传递

Scalar values are immutable in all oop languages, you need a new class

var BooleanBuilder = function( data ){ this._data = !!data; };

BooleanBuilder.prototype.valueOf = function() {
    return this._data;
};
BooleanBuilder.prototype.invert = function() {
    this._data = !this._data;
};

var bool = new BooleanBuilder(true);
alert(bool.valueOf());
bool.invert();
alert(bool.valueOf());  // false

but this is not so smart, you can store the boolean-value in one object and pass this object as reference

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文