vendredi 24 avril 2015

Correct JavaScript 6 type to use for c# equivalent of struct

I'm still getting used to working with JavaScript after many years of working mostly in C#.

I have an object that I'd like to instantiate. The object always has the same 7 fields in it. It's used to easily pass a set of 7 numbers around to various functions.

var myObj = { 
    4: 0,
    6: 0,
    8: 0,
    10: 0,
    12: 0,
    20: 0,
    100: 0
};

In EMCAScript 6, classes have been defined, but from what I've found on the web, classes seem mostly used for defining functions on a class, similar to the prototype of an EMCAScript 5 function, and not for defining fields.

What's the proper way to do this?

My thinking right now is it's something like:

var myObj = function () {
    this[4] = 0;
    this[6] = 0;
    this[8] = 0;
    this[10] = 0;
    this[12] = 0;
    this[20] = 0;
    this[100] = 0;
};

var obj = new myObj();

I don't believe this is a matter of opinion. In most languages, there is a right way to do this.

The way you would do this in C# is

struct MyObj {
    public int Fours { get; set; }
    public int Sixes { get; set; }
    public int Eights { get; set; }
    public int Tens { get; set; }
    public int Twelves { get; set; }
    public int Twenties { get; set; }
    public int Hundreds { get; set; }
}

Aucun commentaire:

Enregistrer un commentaire