0

Can we simply assign a value rather than using Object.create?

Rectangle.prototype = Shape.prototype;
Rectangle.prototype = 
Object.create(Shape.prototype)

what is the difference between the above two statements?

1 Answers1

2

The Object.create() method creates a new object, using an existing object to provide the newly created object's proto . so, if you directly assign a value to an object there is a chance that the assigned object can also mutate here is an example.

let k = {a:12, b:34};
let j = k;
console.log(`k before mutation ${JSON.stringify(k)}`);
j.b = "Mutated";//Updating j changes k too
console.log(`k after mutation ${JSON.stringify(k)}`);

where as Object.create won't mutate

let k = {a: 123, b: 34};
let j = Object.create(k);
console.log(`k before mutation ${JSON.stringify(k)}`);
j.b = "this won't mutate k";
console.log(`k after mutation ${JSON.stringify(k)}`);
karthik
  • 1,100
  • 9
  • 21