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 Properties JavaScript objects inherit the properties of their prototype.
The delete keyword does not delete inherited properties, but if you delete a prototype property, it will affect all objects inherited from the prototype.
I'm kinda lost here... I know that sounds dumb but I need to understand exactly what that means during processes and applications where that might come to play.
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;
}
来源:https://stackoverflow.com/questions/43297451/clarification-on-the-inability-of-javascript-deleting-inherited-properties