Structs in Javascript

后端 未结 8 1358
花落未央
花落未央 2020-12-12 09:29

Previously, when I needed to store a number of related variables, I\'d create a class.

function Item(id, speaker, country) {
    this.id = id;
    this.speak         


        
相关标签:
8条回答
  • 2020-12-12 10:04

    The only difference between object literals and constructed objects are the properties inherited from the prototype.

    var o = {
      'a': 3, 'b': 4,
      'doStuff': function() {
        alert(this.a + this.b);
      }
    };
    o.doStuff(); // displays: 7
    

    You could make a struct factory.

    function makeStruct(names) {
      var names = names.split(' ');
      var count = names.length;
      function constructor() {
        for (var i = 0; i < count; i++) {
          this[names[i]] = arguments[i];
        }
      }
      return constructor;
    }
    
    var Item = makeStruct("id speaker country");
    var row = new Item(1, 'john', 'au');
    alert(row.speaker); // displays: john
    
    0 讨论(0)
  • 2020-12-12 10:08

    I always use object literals

    {id: 1, speaker:"john", country: "au"}
    
    0 讨论(0)
提交回复
热议问题