强制对象评估为假 [英] Force an object to evaluate to false
问题描述
我猜想这可能是特定于应用程序的,但是我使用的是node.js-只要它在v8引擎中都能工作,我就不会在意.
I'm guessing this is probably application specific however I am using node.js - as long as it works in the v8 engine, I don't mind.
我正在尝试创建一个评估为false的 Object
,例如:
I'm trying to create an Object
that evaluates to false, for example:
var Foo = function() { return this; }
var bar = new Foo;
if (bar) // returns false;
是否可以通过覆盖对象的某些功能(例如 toString
?
Is this possible by overriding a certain function of the object, e.g. toString
?
万一有人想知道它可能有什么用例:用于从通常返回布尔值但也可能遇到错误并返回我的自定义错误对象的函数中返回错误对象.
In case anyone is wondering what use case this may have: it is for returning error objects from functions that normally return a boolean value, but could also possibly have encountered an error and returned my custom error object.
我希望以下任何条件函数都可以像该函数返回一个假值,而不必修改条件以适应非布尔值的可能性.
I want any following conditionals to act as if the function returned a false value without having to modify the conditionals to accommodate for the possibility of a non boolean value.
推荐答案
您能获得的最接近的是
if (+obj)
其中一个虚假对象定义了一个 .valueOf()
函数,该函数返回 0
或 false
:
Where a falsy object defines a .valueOf()
function that returns 0
or false
:
var o = {
valueOf: function() {
return false;
}
};
if (+o) {
throw unreachable();
}
这篇关于强制对象评估为假的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!