There are few interesting ways to create Objects on JS
Creating Objects on JS
Constructor function (classical inheritance pattern)
1 |
function myObject(){}; |
Literal notation (prototypal inheritance pattern)
1 |
var myObject={}; |
Object-Based (ES5)
1 |
Object.create() |
DEFINING Methods and Properties:
Constructor Way
1 2 3 4 5 6 |
function myObject(){ this.iAm = 'an Object'; this.iAmFun = function(){ alert('this.iAm') } } |
Literal Way
1 2 3 4 5 6 |
var myObject = { iAm: 'an Object', iAmFun: function(){ alert(this.iAm); } } |
Object-based (ES5)
1 2 3 |
var A = { 'iAm':'an Object'}; var B = Object.create(A); var C = Object.create(B); |
Using them
Constructor Way
1 2 |
var myNewObject = new myObject(); myNewObject.iAm; // "an Object" |
Literal Way
1 |
myObject.iAm; // "an Object" |
Object-based (ES5)
1 |
C; // {iAm: "an Object"} |
Final results:
Constructor Way
Literal Way
Object-based (ES5)
Final notes
Because of simplicity ES5 Object-Based sounds a good option, , we are not using new operator because we are using objects and not functions. Also it is well supported by legacy devices and browsers, or we can get the polyfill