Monday, October 3, 2011

Enums in JavaScript

Originally published 2008-12-27, on tom-ash.net

JavaScript does not support enums like these in C#:
        enum SpriteSize
        {
            Small = 100,
            Big = 200
        }
        
        void Render(SpriteSize spriteSize)
        {
            if (spriteSize == SpriteSize.Small)
            {
            // TODO: implement
            }
        }


The simplest way to get enum functionality in JavaScript is to create a variable using JSON:
<script type="text/javascript">
            var SpriteSize = 
            {
                Small: 100,
                Big: 200
            }

            function Render(spriteSize)
            {
                if (spriteSize == SpriteSize.Small)
                {
                // TODO: implement
                }
            }
</script>

No comments:

Post a Comment