Home > Web Front-end > JS Tutorial > body text

Use of JavaScript delete attribute

高洛峰
Release: 2017-01-20 10:55:24
Original
1022 people have browsed it

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){ 
// 一些关键代码... 
// .... 
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!