OO Javascript 是否有 `to_bool` 或 `__len__` 等价物? [英] Does OO Javascript have a `to_bool` or `__len__` equivalent?

查看:26
本文介绍了OO Javascript 是否有 `to_bool` 或 `__len__` 等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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__` 等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆