How do I remove all attributes from a Javascript object?
For example; if I have the following 'class' how can I perform a reset and remove all its attributes:
function MyObject()
{
this.type="blah";
this.name="kkjkj";
}
MyObject.prototype.clearAttribs = function()
{
// I want to remove name, type etc from 'this'
// Maybe I can do the following?
for (var key in this)
delete this[key];
}
How do I remove all attributes from a Javascript object?
For example; if I have the following 'class' how can I perform a reset and remove all its attributes:
function MyObject()
{
this.type="blah";
this.name="kkjkj";
}
MyObject.prototype.clearAttribs = function()
{
// I want to remove name, type etc from 'this'
// Maybe I can do the following?
for (var key in this)
delete this[key];
}
Share
Improve this question
asked Apr 13, 2012 at 2:33
sazrsazr
26k70 gold badges214 silver badges387 bronze badges
4
- Why would you want to do something like this? – chuckj Commented Apr 13, 2012 at 2:44
- Do you want to delete only data properties or methods/function properties also? – jfriend00 Commented Apr 13, 2012 at 2:51
- @jfriend00 I dont want to delete prototype functions but if an object has an attribute with a function in it then I want to delete it. For eg; myObj.specFunct = function() {}; then I want to delete that. – sazr Commented Apr 13, 2012 at 2:53
- Then, your current code is fine. – jfriend00 Commented Apr 13, 2012 at 2:57
1 Answer
Reset to default 6Your code seems fine as is. Since delete
will not delete a property from the prototype, you do not even need to use hasOwnProperty
.