OO Javascript 是否有 `to_bool` 或 `__len__` 等价物?

2022-01-19 00:00:00 oop boolean instance casting javascript

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.

相关文章