Keshav Jha
Keshav Jha

Reputation: 31

Why does delete operator does not work on an Object created with Object.create() method

Why does delete operator not working on object's created using Object.create() method.

var Dog = {
  name: 'tommy',
  height: '4'
};

var newDog = Object.create(Dog);

delete newDog.name

console.log(newDog.name) // still returns "tommy"

Upvotes: 0

Views: 1334

Answers (3)

JoshG
JoshG

Reputation: 6735

delete indeed removes a property from an object. But if the object inherits the property you're trying to delete, rather than having its own property with that name, delete won't work. You're essentially trying to remove something that doesn't exist. The property you're trying to delete is a property of the object's prototype (or elsewhere in the object's prototype chain), not the object that inherits it.

You can check if an object's property is its own using yourObject.hasOwnProperty(). If hasOwnProperty() returns true, then you can use delete to remove that property.

Otherwise, you'd have to remove the property from the "parent" object.

Upvotes: 2

Sagar Agrawal
Sagar Agrawal

Reputation: 657

When you delete the property from newDog, it does delete the property. You can console the object and see. However, when you call again newDog.name, internally the prototype (of newDog) is set to Dog. So since newDog.name doesn't exists, it goes up the prototypical chain and it finds that property on the Dog object and it prints that value.

Upvotes: 0

Nithya Rajan
Nithya Rajan

Reputation: 4884

Object.create() method is used to create a new object which extends the existing object which you have passed, in your case it's Dog object.

When you delete the name property in your newDog object, it deletes perfectly, but the inherited name property from the Dog object is still there. so you should delete that too.

var Dog = {
  name: 'tommy',
  height: '4'
};

var newDog = Object.create(Dog);

delete newDog.name; // It deletes the property in the newDog, but still the Dog property contains the name property so when you console.log(newDog.name) it prints Dog.name property.

console.log(newDog.name)

delete Dog.name;

console.log(newDog.name); // now it's deleted

Upvotes: 4

Related Questions