问题描述
OO JS 是否有将实例对象转换为布尔值的机制?我希望能够在条件句中直接使用自定义实例对象,并按照 !!(new Foo(0)) === false, !!(newFoo(1)) === true.
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 有
__nonzero__和__len__(参见 这里)
Ruby 有 to_bool.
JS如何对字符串字面量""和零0做到这一点?
How does JS do this for String literals "" and zero 0?
推荐答案
不,JS 没有提供强制转换为布尔值的陷阱方法.值的真实性静态确定由语言规则和无法更改.
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() 或任何概念你的对象代表.
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__` 等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)