We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

rolandog on 07/19/06


Tagged

javascript prototype Objects properties


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

xaviaracil
rolandog


Public properties for Objects in Javascript


Published in: JavaScript 


URL: http://rolandog.com/archives/2006/07/18/konstructor

This function allows an object's property names to be read by using an index. The properties can be accessed like: someobject.propertyNames[0] or someobject.propertyValues[0]. But you first have to make the object's properties available by calling someobject.makePublic(['name1','name2','name3',...,'nameN']). The array in the makePublic function is an array of the names of the properties you'd like to make available. Perhaps you're only interested in ['foo','bar']. This is useful for situations where you don't explicitly know if an object carries all properties, but you have an array of all the possible properties available.

  1. /* Makes the properties you pass in an array publicly available
  2. to access with an index: foo.propertyNames[0]; */
  3. Object.prototype.makePublic=function(array){
  4. var j=0;this.propertyNames=[];this.propertyValues=[];
  5. for(var i=0;i<array.length;++i){
  6. if(this[array[i]]!==undefined){
  7. this.propertyNames.push(array[i]);
  8. this.propertyValues.push(this[array[i]]);
  9. ++j;
  10. }
  11. }
  12. var r=j?j:false;
  13. return r;
  14. };
  15.  
  16. /* Example:
  17. //Creating some 'attributes' in an Object called 'a'.
  18. var a={href:"http://example.com",rel:"me",title:"mypage"};
  19.  
  20. //Making only the object's 'href' attribute available, and assigning the length to a variable.
  21. var l=a.makePublic(['href']);
  22.  
  23. //Alerting the first property name publicly available, along with its value.:
  24. alert(a.propertyNames[0]+"= "+a.propertyValues[0]);
  25. */

Report this snippet 

You need to login to post a comment.