Does OO Javascript have a `to_bool` or `__len__` equivalent?

前端 未结 1 1419
走了就别回头了
走了就别回头了 2020-12-12 01:37

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 alo

1条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-12 01:48

    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.

    You should give your instances a method to be explicitly invoked like isValid(), isTruthy(), isEmpty() or whatever concept your object represents.

    0 讨论(0)
提交回复
热议问题