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

前端 未结 8 2063
清酒与你
清酒与你 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:30

    try this:

    function MyObject(city, town) {
      this.city = city;
      this.town = town;
    }
    
    MyObject.prototype.print = function() {
      alert(city + " " + town);
    }
    
    obj = new MyObject("myCity", "myTown");
    obj.print();
    

提交回复
热议问题