--- there are multiple methods to create multiple obj's.
1) By using object literals.
2)By using the factor function.
3)By using a constructor function.
4) By using JS classes.
---object literal -
ex:-
let obj = {
name : "something",
age : 00,
journey : function(){
console.log("started")
}
};
(for obj literal we create multiple objs individually)
-----------------------------------------------------
---factory function-
(factory function is any function that returns a new OBJ for every function call)
ex:-
function createBike(color, brand) {
return {
color: color,
brand: brand,
start :function(){
console.log("started")
}
};
}
(we can also use the short-hand notation for keys and values inside an obj )
ex:- {
color,
brand,
}
we've to make sure that the keys and parameter names matches accurately while using the short-hand method.
uses camelCase notation.
let bike1 = createBike("red", "ninja");
let bike2 = createBike("blue","ola");
etc.... (when we make a function call with args we get a new obj)
-----------------------------------------------------
---Constructor function-
A regular function that returns a new object on calling with new operator.
function CallingFun(color, brand){
this.color = color;
this.brand = brand;
this.start = function(){
console.log("started")
}
let obj1 =
new CallingFun("blue","audi");
let obj2 =
new CallingFun("red","bmw");
etc.....
The created obj (obj1, obj2).... is called an instance.
obj1.color, obj1.brand is called an instance properties.
obj1.start is called an instance method.
This
keyword refers to the newly created object.
when a function is called with new operator it will create a empty obj and assign it to this variable and returns this.
When the constructor function is called using the new operator and no value is passed, the this keyword will refer to the global object.
uses PascalCase notation.
---ByUsingClass-
class Person {
constructor(name, age) {
this.name
= name;
this.age = age; }
}
const person1 = new Person("John Doe", 30);
const person2 = new Person("Jane Doe", 25);
person1.sayHello();
person2.sayHello();
<<< Thanks for reading />>>