Is there a way I can do all of this in a constructor?
  obj = new Object();
  obj.city = "A";
  obj.town = "B";
                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.
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.
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 ( {} ).
Prototype is used to add new properties and methods to an object.
Why don't you just do it this way:
var obj = {"city": "A", "town": "B"};
                        Like so:
var obj = {
    city: "a",
    town: "b"
}
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With