Different ways of creating Objects in JavaScript
Explained below are some of the different ways of creating Objects in JavaScript.
- Objects created with syntax constructs (Object Literal Notation)
- With Function (New Objects with Constructor function)
A constructor is a function that contains instructions about the properties of an object when that object is created and assigned. Advantage over object literal is you can create many instances of objects that have the same properties.
- With Object.create
ECMAScript 5 introduced a new method Object.create.
- With Class
JavaScript classes were introduced in ECAMScript 2015 (ES6)
Reference
What is prototype and prototype chain in JavaScript
Each JavaScript object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until a object is reached with null as its prototype. null has no prototype and acts as the final link in this prototype chain.
Multiple inheritance with prototypes is referred to as a prototype chain.
To check whether an object has a property defined on itself
and not somewhere on its prototype chain, it is necessary to use the
hasOwnProperty
method which all objects inherit from Object.prototype
.
All functions have a special property named prototype
.
References:
Constructor in JavaScript
A constructor in JavaScript is a function that is called with the “new” operator.
Difference between scope and context in JavaScript
Difference is scope is function based and context is object based.
Scope
Variables can have either local or global scope. Local variables exist only within the function in which they are defined. Variable declared outside the function can be accessed and modified by another function also.
Context
Context this
is set to the object the function is called on.
Reference
How to create a class in JavaScript
In JavaScript classes can be created using functions. Let’s see how.
The method getInfo() gets recreated every time we create a new object. Instead we can add getInfo() to the prototype.