Skip to content Skip to sidebar Skip to footer

Clarification On The Inability Of Javascript Deleting Inherited Properties.

guys. I'm studying up on properties for objects and one thing caught my eye on a source of info. There was this one part of the whole document that stated this about JS. Prototype

Solution 1:

delete removes a property from an object. If the object inherits the property rather than having its own property with that name, calling delete on the property doesn't do anything: You can't remove something that isn't there. :-) It's the object's prototype (or its prototype, or its prototype's prototype, etc.) that has the property, not the object inheriting it.

An example would probably help. Consider:

// An object to use as a prototypevar p = {answer: 42};
// An object using `p` as its prototypevar o = Object.create(p);

console.log(p.answer);                   // 42console.log(p.hasOwnProperty("answer")); // trueconsole.log(o.answer);                   // 42console.log(o.hasOwnProperty("answer")); // false

p has the property, not o; o just inherits it. Like this:

                          +−−−−−−−−−−−−−−−+
p−−−−−−−−−−−−−−−−−−−−−−+−>|   (object)    |
                       |  +−−−−−−−−−−−−−−−+
                       |  | [[prototype]] |−−−>(Object.prototype)
                       |  | answer: 42    | 
     +−−−−−−−−−−−−−−−+ |  +−−−−−−−−−−−−−−−+
o−−−>|    (object)   | |
     +−−−−−−−−−−−−−−−+ |
     | [[Prototype]] |−+
     +−−−−−−−−−−−−−−−+

So delete o.answer has no effect; o has no answer property for delete to remove. p is the object with answer.

If we remove the property from p (delete p.answer;), that will remove it — from p. And since prototypical inheritance is a live connection between an object and its prototype, asking o for answer after doing that will give us undefined, since o (effectively) asks p for it, and p doesn't have it anymore:

// An object to use as a prototypevar p = {answer: 42};
// An object using `p` as its prototypevar o = Object.create(p);

console.log(p.answer);                   // 42console.log(p.hasOwnProperty("answer")); // trueconsole.log(o.answer);                   // 42console.log(o.hasOwnProperty("answer")); // falsedelete o.answer;                         // No effectconsole.log(p.answer);                   // 42console.log(o.answer);                   // 42delete p.answer;                         // Removes it from pconsole.log(p.answer);                   // undefinedconsole.log(o.answer);                   // undefined
.as-console-wrapper {
  max-height: 100%!important;
}

Post a Comment for "Clarification On The Inability Of Javascript Deleting Inherited Properties."