[英]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). 我尝试扩展其truthy
为false
类型,但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.