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 prototype
var p = {answer: 42};
// An object using `p` as its prototype
var o = Object.create(p);
console.log(p.answer); // 42
console.log(p.hasOwnProperty("answer")); // true
console.log(o.answer); // 42
console.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 prototype
var p = {answer: 42};
// An object using `p` as its prototype
var o = Object.create(p);
console.log(p.answer); // 42
console.log(p.hasOwnProperty("answer")); // true
console.log(o.answer); // 42
console.log(o.hasOwnProperty("answer")); // false
delete o.answer; // No effect
console.log(p.answer); // 42
console.log(o.answer); // 42
delete p.answer; // Removes it from p
console.log(p.answer); // undefined
console.log(o.answer); // undefined
.as-console-wrapper {
max-height: 100% !important;
}