I'm writing an implementation of ES Harmony Symbol
/Name
in ES5. I'm going to use the name Symbol
, but I want the browser to use any pre-existing Symbol
it has in the case that it already exists (in future browsers). I want my code to be ES5 strict compliant and portable to other projects.
Here's one way (of many) to do what I want to in ES3/ES5 non-strict:
(function() {
// If Symbol already exists, we're done.
if(typeof Symbol != 'undefined') return;
// This becomes global because it wasn't declared with var
Symbol = function() {
// ...
};
})();
However, it's not ES5 strict compliant because Symbol
is not defined explicitly.
Other ways to accomplish this would involve accessing the window
object (window.Symbol = ...
), but this is no good either because I don't want my code to assume its running in a browser environment.
How can this be done in ES5 strict?