JavaScript Object Prototype
Object⚑
Object is Class
. Almost everything in JavaScript is Object.
All JavaScript values, except premitives, are object.
Object Properties⚑
Named value in JavaScript objects are called properties. example:
const person = {
name: 'Jon',
age: 23
}
person.name // property
person.age // property
Accessing Object Properties⚑
Object properties can be accessed in multiple ways.
person.name
person["name"]
const x = "name"; person[x]
Object Methods⚑
An Object property is an Object method containing function definition. example:
const person = {
name: 'Jon',
age: 23,
sayHi() {
console.log("Hi, " + this.name);
}
}
person.sayHi // method
Accessing Methods⚑
Similar to accessing object properties, methods can be accessed in multiple ways.
person.sayHi()
person["sayHi"]()
const x = "sayHi"; person[x]()
Object Creation⚑
Objects can be created in multiple ways. Following are the ways explained in detail.
Object Literal⚑
Most simplest list
of key: value
pair inside curly braces {}
const person = {
name: 'Jon'
}
Using new
Keyword⚑
If Object()
is invoked with a new
keyword, it will return an object.
const person = new Object();
person.name = 'jon';
person.sayHi = function sayHi() {
console.log("Hi, " + this.name);
}
Using Constructor⚑
To create constructor is nothing but a function invoked with new keyword.
function Person (name) {
this.name = name;
}
Person.prototype.sayHi = function sayHi() {
console.log("Hi, " + this.name);
}
const person = new Person('Jon');
person.name // prop
person.sayHi // method
The first two ways of defining objects does exactly the same thing. It’s better to use object literals to create objects in terms of performence, readablity and execution speed.
Object Mutablity⚑
JavaScript objects are mutable by default. Meaning, they can be easily modified after they are defined.
When new variable, the new variable would point to the location of old object instead of copying it. example:
const person = { name: 'Jon', age: 23 };
const person2 = person; // person === person2
Looping in Object⚑
TBD