JS 中枚举的使用方法

在JavaScript目前的版本中,没有枚举这个概念(当然,ECMA-262第三版中已经将enum作为关键字保留)。
然而,如同JavaScript中没有class一样,但我们仍然可以通过间接的方式——JSON来实现它。

  如下,我们来定义Week的枚举:
        if(typeof WeekDay == "undefined"){
            var WeekDay = {};
            WeekDay.Sunday = 0;
            WeekDay.Monday = 1;
            WeekDay.Tuesday = 2;
            WeekDay.Wedesay = 3;
            WeekDay.Thursday = 4;
            WeekDay.Friday = 5;
            WeekDay.Saturday = 6;
        }

  测试如下:
            alert(WeekDay.Monday);  // -----> Output: 1

 
  当然,我们有更为直观的方式。以定义DOM文档节点类型为例,定义方式如下:
        if(typeof Node == "undefined"){
            var Node = {
                ELEMENT_NODE: 1,
                ATTRIBUTE_NODE: 2,
                TEXT_NODE: 3,
                CDATA_SECTION_NODE: 4,
                ENTITY_REFERENCE_NODE: 5,
                ENTITY_NODE: 6,
                PROCESSING_INSTRUCTION_NODE: 7,
                COMMENT_NODE: 8,
                DOCUMENT_NODE: 9,
                DOCUMENT_TYPE_NODE: 10,
                DOCUMENT_FRAGEMENT_NODE: 11,
                NOTATION_NODE: 12
            }
        }

你可能感兴趣的:(Cocos2d-JS)