JavaScript objects are composite variables that contain many values.  We declare an object using var keyword. We can create JavaScript objects and assign initial value using JSON = Java Script Object Notation.

 

Example:

var person = {
    firstName : "John",
    lastName  : "Doe",
    age       : 50,
    eyeColor  : "blue",
    fullName  : function () {
      return this.firstName + " " + this.lastName}
};

In this example we declare an object person that has several properties and one method. A method is a property of type function. The method name in this example is fullName(). Observe that method fullName() is encolded inside brackets {…} and belong to person object.

 

Object Members

You can access object properties in two ways:

objectName.propertyName

objectName[“propertyName”]

You access an object method with the following syntax:

objectName.methodName();

Alert: We can assign to a variable a function. Therefore do not forget to use parentheses () for a function call. Otherwise you can assign to a variable the function itself by mistake !

 

Alternative Methods

There are two alternative methods to create objects.

  • By using constructor: new Object()
  • By using method: Object.create()

 

JavaScript has predefined objects. One of these is the funamental Object.

The Fundamental Object constructor can be used to create new objects. This is an alternative method to JSON initializer.

Example:

// equivalent to o = new Boolean(true);
var o = new Object(true);

// equivalent to o = new Boolean(false);
var o = new Object(Boolean());

Object prototype

Object.create() method can be used to create new object with the specified prototype object and properties.

Example:

function Shape() {
  this.name = 'Shape 1';
}

function Rectangle() {
  Shape.call(this);
}

Rectangle.prototype = Object.create(Shape.prototype);
const rect = new Rectangle();

console.log(rect.name);
// expected output: "Shape 1"

Function Object

Every JavaScript function is actually a Function object.

var sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6));
// expected output: 8

More details about Objects in JavaScript here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects