Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between object assignment '=' and Object.create()

I am going some deep into javascript object operations. Here my question is what is a different between const me = Object.create(person); and const me = person; here both operation gives me a slimier output. I mean it references object to new variable me.

const person = {
  isHuman: false,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);

me.name = 'Matthew';  
me.isHuman = true;

me.printIntroduction();

const me2 = person;

me.name = 'Manan'; 
me.isHuman = false; 

me.printIntroduction();

In above code I have included both operation direct assignment and assign by using Object.create();. Here both variable referencing to objects person, but what is different between it? Can some one explain me? This question might be asked before but I cant find proper explanation. Simple explanation would be appreciated :-).

like image 678
manan5439 Avatar asked Jan 25 '23 23:01

manan5439


1 Answers

The first difference is that, when you use regular assignment both of your variables point to the same object, when you edit one, you edit the other. This does not happen with create.

const a = {};
const b = a;

b.do = 100;

console.log(a);

const c = Object.create(a);
c.dodo = 100;
console.log(a)

The 2nd difference, is that Object.create creates an object which has the first oject as a "prototype". Prototypes are the basis of how objects and inheritance works in javascript, for example when you have an object, it's default toString method is in the prototype. See this below

const a = {do : 100};
const c = Object.create(a);
console.log(c.do);
console.log(a.hasOwnProperty("do"));
console.log(c.hasOwnProperty("do"));

If yout run the above in a browser console and then log c, you will see that the do is in the __proto__ of c. not directly on c.

Whenever you have any object in javascript and call a property or a method on it, javascript will search it on that object an then go up the prototype chain. This allows you to save space so not every object has to carry the shared properties on it.

Fun side note, {} has all the functions objects have in its prototype, null does not so

const a = Object.create(null);

// works as normal
console.log(a);
a.hello = "hello";
console.log(a);

// error
console.log(a.toString());
console.log(m + m);

EDIT : Sorry, slight mistake when you use Object.create and the edit the original, you do see the change appear in the prototype of the new.

like image 80
QurakNerd Avatar answered Jan 27 '23 13:01

QurakNerd