Should I use object literals or constructor functions?

I am embarrassed how I should create an object in javascript. There seem to be at least two ways. One of them is to use the symbol of the object, while the other uses the construction functions. Is there one advantage over one over the other?

+75
javascript
Feb 01 '11 at 6:57
source share
9 answers

If you don't have the behavior associated with the object (i.e. if the object is just a container for data / state), I would use an object literal.

var data = { foo: 42, bar: 43 }; 

Apply the KISS Principle . If you need nothing but a simple data container, go to a simple literal.

If you want to add behavior to your object, you can go with the constructor and add methods to the object at build time or provide a prototype of your class.

 function MyData(foo, bar) { this.foo = foo; this.bar = bar; this.verify = function () { return this.foo === this.bar; }; } // or: MyData.prototype.verify = function () { return this.foo === this.bar; }; 

A similar class also acts as a schema for your data object. Now you have some kind of contract (through the constructor) which properties the object initializes / contains. A free literal is just an amorphous data frame.

You can also have an external verify function that acts on a plain old data object:

 var data = { foo: 42, bar: 43 }; function verify(data) { return data.foo === data.bar; } 

However, this is not beneficial for encapsulation: ideally, all data + behavior associated with the entity should live together.

+104
Feb 01 2018-11-11T00:
source share

This essentially boils down to whether you need multiple instances of your object or not; an object defined using the constructor allows you to have multiple instances of this object. Object literals are basically singleton with variables / methods that are publicly available.

 // define the objects: var objLit = { x: 0, y: 0, z: 0, add: function () { return this.x + this.y + this.z; } }; var ObjCon = function(_x, _y, _z) { var x = _x; // private var y = _y; // private this.z = _z; // public this.add = function () { return x + y + this.z; // note x, y doesn't need this. }; }; // use the objects: objLit.x = 3; objLit.y = 2; objLit.z = 1; console.log(objLit.add()); var objConIntance = new ObjCon(5,4,3); // instantiate an objCon console.log(objConIntance.add()); console.log((new ObjCon(7,8,9)).add()); // another instance of objCon console.log(objConIntance.add()); // same result, not affected by previous line 
+76
Oct 01
source share

Another way to create objects in a unified form is to use a function that returns an object:

 function makeObject() { var that = { thisIsPublic: "a public variable" thisIsAlsoPublic: function () { alert(that.thisIsPublic); } }; var secret = "this is a private variable" function secretFunction() { // private method secret += "!"; // can manipulate private variables that.thisIsPublic = "foo"; } that.publicMethod = function () { secret += "?"; // this method can also mess with private variables } that.anotherPublicVariable = "baz"; return that; // this is the object we've constructed } makeObject.static = "This can be used to add a static varaible/method"; var bar = makeObject(); bar.publicMethod(); // ok alert(bar.thisIsPublic); // ok bar.secretFunction(); // error! bar.secret // error! 

Since functions in JavaScript are closures, we can use private variables and methods and avoid new .

From http://javascript.crockford.com/private.html from private variables in JavaScript.

+7
Oct 01
source share

It depends on what you want to do. If you want to use (semi-) private variables or functions in an object, this could be a constructor function. If your object contains only properties and methods, the object literal is beautiful.

 function SomeConstructor(){ var x = 5; this.multiply5 = function(i){ return x*i; } } var myObj = new SomeConstructor; var SomeLiteral = { multiply5: function(i){ return i*5; } } 

Now the multiply5 method in myObj and SomeLiteral does the same. The only difference is that myObj uses a private variable. The latter may be useful in some cases. In most cases, the Object literal is sufficient and a good and clean way to create a JS object.

+5
Feb 01 2018-11-11T00:
source share

The code below shows three methods for creating an object, the Object Literal syntax, the function constructor, and Object.create() . The literal syntax of an object simply creates the object on the fly, and therefore its __prototype__ is an Object , and it will have access to all the properties and methods of Object . Strictly in terms of design pattern, a simple Object literal should be used to store one instance of the data.

The constructor of the function has a special property called .prototype . This property will become __prototype__ any objects created by the function constructor. All properties and methods added to the .prototype property of the .prototype constructor will be available to all objects that it creates. A constructor should be used if you require multiple instances of data or require behavior from your object. Note that the function constructor is also best used when you want to simulate a private / shared development pattern. Remember to put all the common methods in .prototype so that they are not created in every instance of the object.

Creating objects using Object.create() uses an object literal like __prototype__ for objects created by this method. All properties and methods added to the object literal will be available for all objects created from it through true prototype inheritance. This is my preferred method.

 //Object Example //Simple Object Literal var mySimpleObj = { prop1 : "value", prop2 : "value" } // Function Constructor function PersonObjConstr() { var privateProp = "this is private"; this.firstname = "John"; this.lastname = "Doe"; } PersonObjConstr.prototype.greetFullName = function() { return "PersonObjConstr says: Hello " + this.firstname + " " + this.lastname; }; // Object Literal var personObjLit = { firstname : "John", lastname: "Doe", greetFullName : function() { return "personObjLit says: Hello " + this.firstname + ", " + this.lastname; } } var newVar = mySimpleObj.prop1; var newName = new PersonObjConstr(); var newName2 = Object.create(personObjLit); 
+4
May 10 '16 at 14:01
source share

Go with the object literal, it is more concretized and expanded with the introduction of initial values.

0
01 Feb 2018-11-11T00:
source share

// Object Literal and Object constructor

 function MyData(foo, bar) { this.foo = foo; this.bar = bar; } MyData.prototype.verify = function () { return this.foo === this.bar; }; //add property using prototype var MD = new MyData;//true. var MD = new MyData();//true. MD.verify// return only the function structure. MD.verify(); //return the verify value and in this case return true coz both value is null. var MD1 = new MyData(1,2); // intialized the value at the starting. MD1.verify// return only the function structure. MD1.verify(); // return false coz both value are not same. MD1.verify(3,3);// return false coz this will not check this value intialized at the top MyData.prototype.verify = function (foo,bar) { return this.foo === this.bar; }; var MD1 = new MyData(1,2); MD1.verify(); MD1.verify(3,3);// return false coz this keyword used with foo and bar that will check parent data 
0
Aug 12 '16 at 8:02
source share

enter image description here

You need a separate instance of the object for the page - Literal.

You want to just pass data like DTO objects, just GET SET: - Literal

You want to create real objects using the method behavior, several instances - the constructor function, follow the principles of OOP, inheritance: - constructor functions.

Below is a youtube video that explains in detail what is literal, what constructor functions, and how they differ from each other.

https://www.youtube.com/watch?v=dVoAq2D3n44

0
Apr 13 '17 at 10:16 on
source share

As mentioned in https://www.w3schools.com/js/js_object_definition.asp

Using the object literal, you define and create , one object, one statement.

Also

An object literal creates only one object. Sometimes we like the type of object that you can use to create many objects of the same type.

0
May 15 '17 at 9:34 a.m.
source share



All Articles