objects
Js is all about object
- creating Objects
- Factories and construction
- primitive and reference type
- working with properties
- private properties
- getter and setter
creating Objects
object literals
const a = {}; // these curly brackets are called object literals
const circle={
radius:4
location:{
x:1
y:2
}
draw:function(){
console.log("draw")
}
}
circle.draw();
factories function
function createCircle(radius){
return{
radius,
draw:function(){
console.log("draw")
}
}
}
const circle=createCircle(5);
circle.draw();
construction function
// start with capital letter
function Circle(radius) {
this.radius = radius;
this.draw = function () {
console.log("draw");
};
}
const functionObj = new Circle(1);
// when we invoke a function with "new" keyword;
//three things happen
// 1 new operator will create empty object
// 2 set this to point to this object
// 3 return automatically this object
construction properties
new Object(); // A new Object object
new String(); // A new String object
new Number(); // A new Number object
new Array(); // A new Array object
new Map(); // A new Map object
new Set(); // A new Set object
new Date(); // A new Date object
new RegExp(); // A new RegExp object
new Function(); // A new Function object
// object literals
/*
but we commonly use object literals instead of creating constructors
*/
// Use object literals {} instead of new Object().
// Use object literals "",'',``, instead of new String().
// Use array literals [] instead of new Array().
// Use pattern literals /()/ instead of new RegExp().
// Use function expressions () {} instead of new Function().
// every object in js have property called constructor
console.log({}.constructor);
Function are objects
function abc() {}
// abc.apply()
// abc.call(),
// abc.name // name of function
// abc.length // length of parameter passed
working with properties
How to loop keys and values how check if key is present in object
private properties
- how to declare private properties