Object

Object is a non-primitive data type in javascript. It is a collection of Properties. A property is an association between key and value. Property's value can also be a function in this case, property is called as method.


Properties

Properties of an object define characteristic of the object. We can say that It is a variable attached to an object. Following are ways we can access property value.

  1. by dot operator. eg: objectName.propertyName
  2. by bracket notation. eg: objectName['propertyName']
let obj = {
a: 'text'
};

// by dot operator
let dotOperator = obj.a; // dotOperator will get value 'text' assigned

// by bracket notation
let bracketWay = obj['a']; // bracketWay will get value 'text' assigned

Method

A method is a property with a function definition. They are actions that performs on an object.

Calling Object Methods:

objectName.methodName()
Following is an example to display name
var obj = {
name: 'tom',
displayName() {
console.log(this.name) // The this refers to the object that it is in.
}
};
obj.displayName(); // prints 'tom' in console

Accessors (Getters and Setters)

Getters and Setters allows to set computed properties. Getters is defined by prefexing 'get' keyword.

Setters are defined by using 'set' keyword

Following is an example to display fullName without using paranthesis.
var obj = {
fName: 'tom',
lName: 'tom',

get fullName() {
console.log(this.fName + ' ' + this.lName) // The this refers to the object that it is in.
}

set firstName(name) {
this.fName = name
}

set lastName(name) {
this.lName = name.split
}
};
obj.firstName = 'john' // sets property fName to 'john'
obj.lastName = 'carter' // sets property lName to 'carter'
console.log(obj.fullName); // prints 'johne carter' in console
// note the above is called as a property not as method.

Constructor

Constructor is a function that is called during initialization/creation of an object.

It is good practice to name constructor function with upper-case first letter.

Following is an example which creates a single object.
var employee1 = {
name: 'tom',
employeeId: 3
};
var employee2 = {
name: 'harry',
employeeId: 6
};
// In the above we can create single object by using {}.
// if we need to create multiple employee using {} then we had to follow above way.
This can be avoided by using constructor (blueprint) for creating many objects of same type. For example,
function Employee(employeeId, name) { // constructor function
this.name = name;
this.employeeId = employeeId;
}

var employee1 = new Employee(2, 'tom') // creates an object of Employee type
var employee2 = new Employee(6, 'harry') // creates an object of Employee type

Prototype

Prototype is a technique by which javascript objects inherit method and property from one another.