1

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);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • That's probably because the object passed into `Object.create()` is used as its prototype, not the actual object. Maybe try `delete Emp1.prototype.company` – somethinghere May 06 '23 at 11:31
  • 1
    https://stackoverflow.com/questions/43297451/clarification-on-the-inability-of-javascript-deleting-inherited-properties – Andy May 06 '23 at 11:31

3 Answers3

3

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:

let Employee = {company: 'xyz'};
let Emp1 = Object.create(Employee);
Emp1.company = 'Emp1s company';
console.log(Emp1.company); // -> 'Emp1s company' (property from Emp1)
delete Emp1.company;
console.log(Emp1.company) // -> 'xyz' (the value from the prototype)

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

Thomas Frank
  • 1,404
  • 4
  • 10
1

From MDN

The Object.create() static method creates a new object, using an existing object as the prototype of the newly created object.

Also

delete only has an effect on own properties. If a property with the same name exists on the object's prototype chain, then after deletion the object will use the property from the prototype chain.

So Emp1.company is, after creation, a reference to Employee.prototype.company and thus can't be deleted. If you want to create a copy of Employee, use {...Employee}. Now you can delete company from it.

const Employee = { company: "xyz" };
const Emp1 = {...Employee };
delete Emp1.company;
console.log(Emp1.company);

// with Object.create ...
const Emp2 = Object.create(Employee);
// here you override Employee.prototype.company
// with a local property (which is retrieved 
// first)
Emp2.company = `abc`;
console.log(Emp2.company, Employee.company);

// remove the local property
delete Emp2.company;
// now Emp2.company finds `company` in its prototype again
console.log(Emp2.company, Employee.company);
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

You have to delete this property from the prototype like this:

delete Object.getPrototypeOf(Emp1).company
adeelch
  • 21
  • 2