Creating JavaScript objects
27 May 2015There are three ways to create objects in Javascript.
Object literal: Easiest and cleanest way to create “one” object. However, Somewhat complex to add functions on prototype.
var foo = { name: "default", age: 25 };
Constructor: Use it if you want to create multiple objects of same type and need more control over the prototype chain.
function Person() { this.name = "default"; this.age = 25;}
Person.prototype.setName = function(val) { this.name = val; }
var p2 = new Person();
Object.Create(proto, prop): This approach is great if you want to create an object from a constructor function, but only inherit Prototype functions not Constructor properties.
var p3 = Object.create(Person.prototype,
{ city:
{ writable: true,
value: "Philly"
}
});
For example, here Person constructor function has name
and age
properties but p3 object will inherit only prototype function i.e. setName().