6

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];
}
4
  • Why would you want to do something like this? Commented Apr 13, 2012 at 2:44
  • Do you want to delete only data properties or methods/function properties also? 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. Commented Apr 13, 2012 at 2:53
  • Then, your current code is fine. Commented Apr 13, 2012 at 2:57

1 Answer 1

6

Your code seems fine as is. Since delete will not delete a property from the prototype, you do not even need to use hasOwnProperty.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.