Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Пример из Флэнагана (https://javascript.ru/forum/misc/74460-primer-iz-flehnagana.html)

RuBrain 14.07.2018 11:12

Пример из Флэнагана
 
Всем привет

Продолжаю ковырять Флэнагана, в книге есть такой пример перечисления:

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


В переменной dime должен создаваться новый объект, но при запуске скрипта, интерпретатор ругается на функцию enumeration. Подскажите, почему не работает код?

рони 14.07.2018 12:21

Цитата:

Сообщение от RuBrain
интерпретатор ругается на функцию enumeration

и где сама функция?

Rise 14.07.2018 13:33

Цитата:

Сообщение от RuBrain
должен создаваться новый объект

Там наверное не объект, а просто значение 10, примитив, вообще странная функция)

RuBrain 26.07.2018 13:08

Прошу прощения, мой косяк, чуть ниже было описание функции. Вот весь код:

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

    // Enumerated values inherit from this object.
    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) {         // For each value 
        var e = Object.create(proto);          // Create an object to represent it
        e.name = name;                   // Give it a name
        e.value = namesToValues[name];   // And a value
        enumeration[name] = e;           // Make it a property of constructor
        enumeration.values.push(e);      // And store in the values array
    }
    // A class method for iterating the instances of the class
    enumeration.foreach = function(f,c) {
        for(var i = 0; i < this.values.length; i++) f.call(c,this.values[i]);
    };

    // Return the constructor that identifies the new type
    return enumeration;
}


// Create a new Coin class with four values: Coin.Penny, Coin.Nickel, etc.
var Coin = enumeration({Penny: 1, Nickel:5, Dime:10, Quarter:25});
var c = Coin.Dime; // This is an instance of the new class


Скажите, как часто на практике вообще применяется подобное?

RuBrain 26.07.2018 16:08

И еще вопрос, в 24 строке определяется метод foreach, что нужно передавать в аргументы при его вызове?

Например я хочу вызвать его у объекта Coin. Что в (f, c) нужно?

Rise 26.07.2018 16:28

Цитата:

Сообщение от RuBrain
как часто на практике вообще применяется подобное?

сложно сказать, практика понятие широкое
Цитата:

Сообщение от RuBrain
в 24 строке определяется метод foreach, что нужно передавать в аргументы при его вызове?

function и context

рони 26.07.2018 18:17

Цитата:

Сообщение от RuBrain
метод foreach, что нужно передавать в аргументы при его вызове?

Цитата:

Сообщение от Rise
function и context

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

    // Enumerated values inherit from this object.
    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) {         // For each value
        var e = Object.create(proto);          // Create an object to represent it
        e.name = name;                   // Give it a name
        e.value = namesToValues[name];   // And a value
        enumeration[name] = e;           // Make it a property of constructor
        enumeration.values.push(e);      // And store in the values array
    }
    // A class method for iterating the instances of the class
    enumeration.foreach = function(f,c) {
        for(var i = 0; i < this.values.length; i++) f.call(c,this.values[i]);
    };

    // Return the constructor that identifies the new type
    return enumeration;
}


// Create a new Coin class with four values: Coin.Penny, Coin.Nickel, etc.
var Coin = enumeration({Penny: 1, Nickel:5, Dime:10, Quarter:25});
var c = Coin.Dime; // This is an instance of the new class
var s = {sum : 0};
function fn(a)
{
    this.sum += a.value
}
Coin.foreach(fn, s);
alert(s.sum)

RuBrain 01.08.2018 22:57

Подскажите, как понять следующий пример с использованием enumeration:

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

    // Enumerated values inherit from this object.
    var proto = enumeration.prototype = {
        constructor: enumeration,                   // Identify type
    };

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

    // Now create the instances of this new type.
    for(name in namesToValues) {         // For each value
        var e = Object.create(proto);          // Create an object to represent it
        e.name = name;                   // Give it a name
        e.value = namesToValues[name];   // And a value
        enumeration[name] = e;           // Make it a property of constructor
        enumeration.values.push(e);      // And store in the values array
    }
    // A class method for iterating the instances of the class
    enumeration.foreach = function(f,c) {
        for(var i = 0; i < this.values.length; i++) f.call(c,this.values[i]);
    };

    enumeration.print = function() {
        console.log(this.values);

    }

    // Return the constructor that identifies the new type
    return enumeration;
}


// Define a class to represent a playing card
function Card(suit, rank) {
    this.suit = suit;         // Each card has a suit
    this.rank = rank;         // and a rank
}

// These enumerated types define the suit and rank values
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});


// Define a class to represent a standard deck of cards
function Deck() {
    var cards = this.cards = [];     // A deck is just an array of cards
    Card.Suit.foreach(function(s) {  // Initialize the array
        Card.Rank.foreach(function(r) {
            cards.push(new Card(s, r));
        });
    });
}

var deck = new Deck();


Не понятно что происходит при создании var deck. Откуда берутся s и r в параметрах , если они не объявлены никак ранее? И как опять тут срабатывает enumeration.foreach = function(f,c), каким образом там оказывается список Card.Suit и Card.Rank, если он не передается в параметрах. Помогите пожалуйста разобраться, уже и так и сяк пробовал дебагером смотреть, ничего не понятно.

RuBrain 02.08.2018 05:50

https://c.radikal.ru/c03/1808/62/76c3d91add9b.png

рони 02.08.2018 08:47

Цитата:

Сообщение от RuBrain
Откуда берутся s и r в параметрах ,

Цитата:

currentValueТекущий обрабатываемый элемент в массиве.
/Array/forEach


Часовой пояс GMT +3, время: 19:36.