Creating a javascript object and filling its properties in one line

Is there a way to do all this in the constructor?

  obj = new Object();
  obj.city = "A";
  obj.town = "B";
+5
source share
8 answers

Why don't you just do this:

var obj = {"city": "A", "town": "B"};
+13
source

Same:

var obj = {
    city: "a",
    town: "b"
}
+5
source
function MyObject(params) {
    // Your constructor
    this.init(params);
}

MyObject.prototype = {
    init: function(params) {
        // Your code called by constructor
    }
}

var objectInstance = new MyObject(params);

, , .

+5

var obj = {
    city : "A",
    town : "B"
};
+2
function cat(name) {
    this.name = name;
    this.talk = function() {
        alert( this.name + " say meeow!" )
    }
} 

cat1 = new cat("felix")
cat1.talk() //alerts "felix says meeow!"
+1

:

function myObject(c,t) {
    this.city = c;
    this.town = t;
}

var obj = new myObject("A","B");
+1

:

function MyObject(city, town) {
  this.city = city;
  this.town = town;
}

MyObject.prototype.print = function() {
  alert(city + " " + town);
}

obj = new MyObject("myCity", "myTown");
obj.print();
0

. .

var Cont = function(city, town) {
           this.city = city;
           this.town = town;
          }

var Obj = new Cont('A', 'B');
0

All Articles