Objects and its Internal representation in JavaScript
As we all know object is a collection of properties and it is associated between a name or key and a value.
for example
If your object is car and properties are color,weight,model etc.,
We can create object in many ways
Object Literal-Direct way
Object.create
Object Instance
Object constructor
object assign
let’s look into each one of them briefly
- A JavaScript object Literal is a comma-separated list of name-value pairs wrapped in curly braces separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array.
For Example
var car= {
color: “white”,
name: “benz”,
price: “27L”,
updateprice: () => {
// logic to update price
},
grade: [‘A’, ‘A+’, ‘A’]
}
2.This method creates a new object with the specified prototype and properties of the old object
For Example
var newstudent=object.create(student){
age:”17"
grade:[“A”,”A+”,”A”]
id:7
name:”Mahesh”
updateAddress:()=>{
//logic of updateaddress}
newstudent;
3.”instance” can be used informally to mean an object created using a particular constructor function.
For Example
const newObj = new Object();
newObj.name = ‘Mahesh’;
newObj.location = ‘Delhi, India’;
4.A constructor is a function that creates an instance of a class which is typically called an “object”. It is called when you declare an object using the new keyword.
For Example
function Vehicle(name, model) {
this.name = name;
this.model = model;
}let car1 = new Vehicle(‘Fiesta’, ‘2019’);
let car2 = new Vehicle(‘DC avanti’, ‘2018’);
5.The method copies all enumerable own properties from one or more source objects to a target objects. It returns the target object.
For Example
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };const returnedTarget = Object.assign(target, source);
console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }