Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an object falsy [duplicate]

Tags:

javascript

Is it possible to override something on an object in JavaScript so that it appears ‘falsy’?

For exampe, I create an object like this:

function BusyState() { 
  var self = this;
  self.isSet = false;
  self.enter = function () { self.isSet = true; };
  self.exit = function () { self.isSet = false; };
};

var isLoading = new BusyState();
isLoading.enter();

I can check for busy like this:

if (isLoading.isSet) 

But I'd like to be able to write this as a shorthand:

if (isLoading) 

Can I do something to my object to have it appear truthy or falsy depending on the value of isSet?

like image 825
Paul Stovell Avatar asked Aug 20 '13 07:08

Paul Stovell


1 Answers

As far as I know this can't be done. If you read the ECMAScript-specification you'll see that if(isLoading) is evaluated as if(ToBoolean(isLoading) === true) and ToBoolean() will always return true for an object (as you can see in the table in the specification).

like image 84
Karl-Johan Sjögren Avatar answered Nov 09 '22 17:11

Karl-Johan Sjögren