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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With