JavaScript类和枚举

时间:2016-12-03 15:34:51

标签: javascript class

我试图理解JavaScript中的枚举类型。有人可以帮忙解释下面的代码吗?

我很难理解枚举函数返回的内容(返回枚举) 这个函数是否返回一个名为Coin的对象有四个值? 最后,第2/3行虚拟构造函数的用途是什么?

 function enumeration(namesToValues) {
        // This is the dummy constructor function that will be the return value.
        var enumeration = function() { throw "Can't Instantiate Enumerations"; };


        var proto = enumeration.prototype = {
            constructor: enumeration,                   // Identify type
            toString: function() { return this.name; }, // Return name
            valueOf: function() { return this.value; }, // Return value
            toJSON: function() { return this.name; }    // For serialization
        };

        enumeration.values = [];  // An array of the enumerated value objects

        // Now create the instances of this new type.
        for(name in namesToValues) {         
            var e = inherit(proto);         
            e.name = name;                   
            e.value = namesToValues[name];   
            enumeration[name] = e;           
            enumeration.values.push(e);       
        }

        enumeration.foreach = function(f,c) {
            for(var i = 0; i < this.values.length; i++) f.call(c,this.values[i]);
        };

        return enumeration;
    }



    var Coin = enumeration({Penny: 1, Nickel:5, Dime:10, Quarter:25});

    var c = Coin.Dime;                   // This is an instance of the new class
    c instanceof Coin                    // => true: instanceof works
    c.constructor == Coin                // => true: constructor property works
    Coin.Quarter + 3*Coin.Nickel         // => 40: values convert to numbers
    Coin.Dime == 10                      // => true: more conversion to numbers
    Coin.Dime > Coin.Nickel              // => true: relational operators work
    String(Coin.Dime) + ":" + Coin.Dime  // => "Dime:10": coerce to string

0 个答案:

没有答案