是否OO的Javascript有一个`to_bool`或`__len__`相同呢? [英] Does OO Javascript have a `to_bool` or `__len__` equivalent?
问题描述
OO JS是否有铸造实例对象为布尔机制?我希望能够使用自定义实例条件语句中的直接对象,并沿行作出断言 !!(新的Foo(0))===虚假
, !!(新的Foo(1))===真
。
Does OO JS have a mechanism for casting instance objects to boolean? I would like to be able to use custom instance objects directly in conditionals, and make assertions along the lines of !!(new Foo(0)) === false
, !!(new Foo(1)) === true
.
-
Python有
__非零__
和__ LEN __
(见的这里)
Ruby有 to_bool
。
如何JS做到这一点的字符串文字,
和零 0
?
How does JS do this for String literals ""
and zero 0
?
推荐答案
没有,JS不提供转换为Boolean陷阱的方法。一个价值感实性是静态的语言规则并确定 不能改变。
No, JS does not provide a trap method for casting to boolean. Truthiness of a value is statically determined by the language rules and cannot be changed.
您应该给您的实例的方法必须显式调用像的isValid()
, isTruthy()
,的isEmpty()
或什么概念你的对象重新presents。
You should give your instances a method to be explicitly invoked like isValid()
, isTruthy()
, isEmpty()
or whatever concept your object represents.
这篇关于是否OO的Javascript有一个`to_bool`或`__len__`相同呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!