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;


const me2 = person;

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


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 26 '23 06:01


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;


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

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);

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
a.hello = "hello";

// error
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 20:01