我想这样做:
a = false;
a.toggle();
console.log(a) // -> true;
所以我创建了这个:
Boolean.prototype.toggle = function (){this = !this; return this;}
但它就是行不通。我也使用 valueOf 等尝试了许多类似的版本,但总是失败。
我怀疑 Boolean
对象在其 prototype
上没有 setter 方法。但也许你们可以帮忙解决这个问题。
提前致谢。
(请不要回答“为什么a = !a
对你没有好处?”)
最佳答案
首先,您永远无法在 javascript 中分配给 this
,因此 this = !this
不起作用。
其次, boolean 对象似乎没有 setter。它有 valueOf()
和 toString()
。
这是我能达到的最接近的结果:
Boolean.prototype.toggle = function (){return !this.valueOf();}
var a = false;
var b = a.toggle();
console.log(b) // -> true;
关于javascript - 扩展 JS Boolean.prototype 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10282821/