Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

  obj = new Object();
  obj.city = "A";
  obj.town = "B";
like image 393
Alan2 Avatar asked Aug 02 '12 12:08

Alan2


People also ask

What is instantiating an object in JavaScript?

An instantiation pattern in JavaScript is a way to create an object using functions. There are five instantiation patterns: Functional, Functional-shared, Prototypical, Pseudoclassical, and ES6.

How do you add a property to an object in JavaScript?

One way is to add a property using the dot notation: obj. foo = 1; We added the foo property to the obj object above with value 1.

How do you initialize an object in JavaScript?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).

Which JavaScript property is used to add new properties and methods to objects?

Prototype is used to add new properties and methods to an object.


3 Answers

Why don't you just do it this way:

var obj = {"city": "A", "town": "B"};
like image 135
nez Avatar answered Sep 19 '22 07:09

nez


Like so:

var obj = {
    city: "a",
    town: "b"
}
like image 39
Austin Avatar answered Sep 20 '22 07:09

Austin


function MyObject(params) {
    // Your constructor
    this.init(params);
}

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

var objectInstance = new MyObject(params);

This would be the prototype way, which i prefere over plain object literals when i need more then one instance of the object.

like image 33
stlvc Avatar answered Sep 20 '22 07:09

stlvc