最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Remove attributes from a Javascript object - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论