skip to Main Content

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


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

    Login or Signup to reply.
  2. 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);
    Login or Signup to reply.
  3. You have to delete this property from the prototype like this:

    delete Object.getPrototypeOf(Emp1).company
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search