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];
}
asked Apr 13, 2012 at 2:33
sazr
26.2k71 gold badges217 silver badges392 bronze badges
-
Why would you want to do something like this?chuckj– chuckj2012年04月13日 02:44:58 +00:00Commented Apr 13, 2012 at 2:44
-
Do you want to delete only data properties or methods/function properties also?jfriend00– jfriend002012年04月13日 02:51:11 +00:00Commented 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– sazr2012年04月13日 02:53:19 +00:00Commented Apr 13, 2012 at 2:53
-
Then, your current code is fine.jfriend00– jfriend002012年04月13日 02:57:38 +00:00Commented Apr 13, 2012 at 2:57
1 Answer 1
Your code seems fine as is. Since delete will not delete a property from the prototype, you do not even need to use hasOwnProperty.
answered Apr 13, 2012 at 2:46
Tikhon Jelvis
68.3k19 gold badges183 silver badges217 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js