js Objects

Object Literal

A JavaScript object literal is a comma-separated list of name-value pairs wrapped in curly braces. Object literals encapsulate data, enclosing it in a tidy package.

an example object literal:

1
2
3
4
5
var myObject = {
sProp: 'some string value',
numProp: 2,
bProp: false
};

Object literal property values can be of any data type, including array literals, functions, and nested object literals.

Object Literal Syntax

Object literals are defined using the following syntax rules:

  • A colon separates property name from value.
  • A comma separates each name-value pair from the next.
  • There should be no comma after the last name-value pair.

several ways how to create object

Objects can be initialized using new Object(), Object.create(), or using the literal notation (initializer notation).

1
2
// Using the Object() constructor:
var d = new Object();
1
2
// Using Object.create() method:
var a = Object.create(null);
1
2
// Using the bracket's syntactig sugar:
var b = {};
1
2
3
4
5
// Using a function constructor
var Obj = function(name) {
this.name = name
}
var c = new Obj("hello");
1
2
3
4
// Using the function constructor + prototype:
function myObj(){};
myObj.prototype.name = "hello";
var k = new myObj();
1
2
3
4
5
6
7
// Using ES6 class syntax:
class myObject {
constructor(name) {
this.name = name;
}
}
var e = new myObject("hello");
1
2
3
4
// Singleton pattern:
var l = new function(){
this.name = "hello";
}