Clarification on the inability of javascript deleting inherited properties.

别等时光非礼了梦想. 提交于 2019-12-01 01:05:28

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!