Home  >  Article  >  Web Front-end  >  Use of JavaScript delete attribute

Use of JavaScript delete attribute

高洛峰
高洛峰Original
2017-01-20 10:55:241054browse

delete is to delete an attribute of the object. For example, for an object,
var obj = {key:5};
delete obj.key is to delete the key attribute of the object. This is no problem, but when the object It is worth noting that this attribute also exists in the prototype object.

var A = function(){}; 
A.prototype.testMe = true; 
var a = new A(); 
//覆盖原型属性 
a.testMe = true; 
if(a.testMe){ 
// 一些关键代码... 
// .... 
//删除这属性 
delete a.testMe; 
} 
//第二段 --------------------------- 
// 在其它模块中 
if(a.testMe){ 
// 一些关键代码... 
// .... 
}

The second paragraph is worth noting. Don’t think that testMe in a will no longer exist after being deleted, so a.testMe is undefined, which is false. In fact, it still exists through prototype access. It’s still true!
I got tricked here if I wasn’t careful.
//Attachment:
Detect whether an object has a certain attribute, including the prototype chain:
if ('attrName' in obj)...
Detecting whether an object has a certain attribute belongs to the object itself, and Non-prototype chain:
obj.hasOwnProperty('attrName')

For more articles related to the use of JavaScript delete attributes, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn