I have defined an object Employee
with a property name company
. After creating a new object Emp1
I tried to delete the property from the object but it still exists under the object Emp1
. What is the reason for it?
var Employee = {
company: 'xyz'
}
var Emp1 = Object.create(Employee);
delete Emp1.company;
console.log(Emp1.company);
3
Answers
You are using Object.create to create an object Emp1 with the object that has the property Employee* as its prototype. So the property is not a part of your Emp1, its part of the prototype object Employee and thus deleting it on Emp1 has no effect.
Try it out yourself: If you added the property to your Emp1 object it would exist until you deleted it:
This is how prototypical inheritance works in JS. A property shadows the same prototype property as long as it exist, if you remove it you get the same property from the prototype if it exists (if not from the prototypes prototype etc.)
(So Object.create is not making a copy – it’s creating an object with another object as its prototype.)
From MDN
Also
So
Emp1.company
is, after creation, a reference toEmployee.prototype.company
and thus can’t be deleted. If you want to create a copy ofEmployee
, use{...Employee}
. Now you can deletecompany
from it.You have to delete this property from the prototype like this: