简体   繁体   English

你可以覆盖JavaScript对象的真实强制吗?

[英]Can you override the truthy coercion of a JavaScript Object?

The string coercion can be overwritten using the toString function. 可以使用toString函数覆盖string强制。

The number coercion can be overwritten using the valueOf function. 可以使用valueOf函数覆盖number强制。

The boolean coercion can be also overwritten using the valueOf function. boolean强制也可以使用valueOf函数覆盖。

 var foo = { toString: function() { console.log("To String"); return "bar"; }, valueOf: function() { console.log("Value Of"); return 5; } }; console.log(`${foo}`); console.log(+foo); console.log(foo == true); console.log(!!foo); 

I haven't been able to find a function that gets called for when an object needs to get converted to a truthy . 当一个对象需要转换为truthy时,我无法找到一个被调用的函数。 Since x == true and !!x have different behaviors, then I am guessing that there is no function that changes that. 由于x == true!!x有不同的行为,所以我猜测没有改变它的功能。 I instead tried extending types whose truthy is false but the only value that gets accepted by Object.create is null which is almost identical to an object literal (has none of the Object.prototype properties). 我尝试扩展其truthyfalse类型,但Object.create接受的唯一值是null ,它几乎与对象文字相同(没有Object.prototype属性)。

foo == true actually converts foo to a number, that's why valueOf works, but it's misleading. foo == true实际上将foo转换为数字,这就是valueOf工作的原因,但这会产生误导。
You can try {} == true here to see which steps of the comparison algorithm are executed (disclaimer: I made that). 你可以在这里尝试{} == true来查看比较算法的哪些步骤被执行(免责声明:我做到了)。

!foo however calls ToBoolean , which explicitly always returns true for an object. 然而, !foo调用ToBoolean ,它明确地总是为对象返回true There is no way to override that behavior. 无法覆盖该行为。

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM