Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript enum sample - how does this work?

This bit of code is from this answer.

I'm trying to understand how it works but I'm not getting it all.

What I think is happening is TEST_ERROR is a closure so ErrorValue can't be changed. One would reference a value like this: TEST_ERROR.SUCCESS. Please correct me if either of those statements are incorrect.

What I don't understand is what the return statement is doing. It's returning an object made up of different ErrorValues, but returning it to what? And what is it returning from? And when is it being called?

var TEST_ERROR = (function() {
  function ErrorValue(value, friendly) {
    this.value = value;
    this.friendly = friendly;
  }
  ErrorValue.prototype = {
    toString: function() { return this.friendly; },
    valueOf: function() { return this.value; }
  };
  return {
    'SUCCESS': new ErrorValue(0, 'Success'),
    'FAIL': new ErrorValue(1, 'Fail'),
    'ID_ERROR': new ErrorValue(2, 'ID error')
  };
})(); 

Thanks!

Paul

like image 885
Paul Avatar asked Jan 21 '23 21:01

Paul


2 Answers

TEST_ERROR is a closure so ErrorValue can't be changed.

TEST_ERROR will end up just being the object specified in the return statement inside the anonymous function. This object can be changed.

One would reference a value like this: TEST_ERROR.SUCCESS

That's correct.

What I don't understand is what the return statement is doing. It's returning an object made up of different ErrorValues, but returning it to what? And what is it returning from? And when is it being called?

The return statement is returning from the anonymous function that's declared with

(function() { ...})();

The () at the end means that the anonymous function is being called immediately after it is declared, and the value inside the return block is assigned to TEST_ERROR

Here's a good article on closures and emulating private variables that might be useful.

like image 124
Andrew Whitaker Avatar answered Jan 30 '23 18:01

Andrew Whitaker


It is returning its result to TEST_ERROR

var TEST_ERROR = 

and it is being called immediately:

})();

This is a common javascript pattern. You create an anonymous function just for the privacy/scoping it provides, then execute it immediately rather than keeping it around.

like image 41
Gabe Moothart Avatar answered Jan 30 '23 19:01

Gabe Moothart