Javascript初学者问题

时间:2017-12-17 11:25:31

标签: javascript function methods

function enumeration(namesToValues) {
    var enumeration = function () { throw "Can't Instantiale Enumerations" };

    var proto = enumeration.prototype = {
        construtor: enumeration,
        toString: function () { return this.name; },
        valueOf: function () { return this.value; },
        toJSON: function () { return this.name; }
    };

    enumeration.values = [];

    for (name in namesToValues) {
        var e = Object.create(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;
}

function Card(suit, rank) {
    this.suit = suit;
    this.rank = rank;
}

Card.Suit = enumeration({ Clubs: 1, Diamonds: 2, Hearts: 3, Spades: 4 });
Card.Rank = enumeration({ Two: 2, Three: 3, Four: 4, Five: 5, Six: 6, Seven: 7, Eight: 8, Nine: 9, Ten: 10, Jack: 11, Queen: 12, King: 13, Ace: 14 });

function Deck() {
    var cards = this.cards = [];
    Card.Suit.foreach(function (s) {
        Card.Rank.foreach(function (r) {
            cards.push(new Card(s, r));
        });
    });
}

我的问题是,当只有一个参数传递给foreach方法时,为什么它会起作用。 该方法应该收到两个参数 - &gt; function(f,c){}

为什么s和r在不断变化,唯一应该改变的变量是this.values [i] ??

function Deck() {
    var cards = this.cards = [];
    Card.Suit.foreach(function (s) {
        Card.Rank.foreach(function (r) {
            cards.push(new Card(s, r));
        });
    });
}

0 个答案:

没有答案