Instantiating a javascript object and populating its properties in a single line

前端 未结 8 2058
清酒与你
清酒与你 2021-01-12 14:50

Is there a way I can do all of this in a constructor?

  obj = new Object();
  obj.city = \"A\";
  obj.town = \"B\";
相关标签:
8条回答
  • 2021-01-12 15:38

    Why don't you just do it this way:

    var obj = {"city": "A", "town": "B"};
    
    0 讨论(0)
  • 2021-01-12 15:54

    Do not complicate things. Here is a simplest way of defining a constructor.

    var Cont = function(city, town) {
               this.city = city;
               this.town = town;
              }
    
    var Obj = new Cont('A', 'B');
    
    0 讨论(0)
提交回复
热议问题