Setting a custom property using DontEnum

If I create:

Object.prototype.count = function() {}; var m = {prop: 1}; for(var i in m) window.status += i + ", "; 

in the above code i also contains count inherited from its prototype. Now I want to know if there is a way to set a custom property as a DontEnum flag (it is not configurable for a custom property), so it will not be listed.

I know that I can do if(m.hasOwnProperty(i)) to check only its property, but if I write a kind of API array that I have to tell the programmer to remember that ... and this is unacceptable!

+4
source share
2 answers

Actually, an Object has a propertyIsEnumerable property, but this is not very useful. Perhaps http://dhtmlkitchen.com/learn/js/enumeration/dontenum.jsp can give you more insight? If you follow the chapters, you will be taken to a page with the simple question “How to set the DontEnum attribute”, the answer was even simpler and rather disappointing: “You cannot.” Fortunately, there are a few more chapters. You should be taken to a page containing an interesting phrase: "Good, good, IE is shit, JavaScript sucks, blah, blah ... time to stop complaining and steer my sleeves." Bottom line of the tutorial: "Enumeration in JavaScript creates a serious problem."

+4
source

Starting with JavaScript 1.8.5, you can use the Object defineProperty method:

 Object.defineProperty (object, propertyName, attributes); 

Where attributes is a map in which you can set various attributes such as value , enumerable and writable . If a property exists, it changes; otherwise, it is created.

Yuri Zaitsev built an ECMAScript 5 compatibility table where you can find browsers that support defineProperty (and many other functions), although Safari does not support defineProperty for DOM objects - just against IE! :( -

EDIT

Yuri updated the table.

+3
source

All Articles