SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Dec 2006
    Posts
    29
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question about prototyping...

    Curious about how prototyping works and if there is a workaround for my problem. Say I create a new function for Objects called 'keyExists':

    Code JavaScript:
    Object.prototype.keyExists=function(key)
    {
       for(var tempKey in this)
          if(tempKey==key)
             return true;
     
       return false;
    };
    When I use this function, one of the keys in the iteration will be the new function that I have created.

    The following example would alert the following: "key1", "key2", "keyExists". The last one is my concern. Obviously their are other browser-defined functions available for Objects that don't show up when iterating through the object. I thought Object.prototype.functionname was the methodology for that but apparently not. Is there a way to achieve the effect I am looking for?

    Code JavaScript:
    Object.prototype.keyExists=function(key)
    {
       for(var tempKey in this)
       {
          alert(tempKey);
     
          if(tempKey==key)
             return true;
       }
     
       return false;
    };
     
    var testObject={"key1":"key1val", "key2":"key2val"};
     
    testObject.keyExists("key3");

  2. #2
    SitePoint Enthusiast
    Join Date
    Aug 2006
    Posts
    41
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    it's accepted by most js developers out there that extending the Object prototype isn't a particularly good idea, for this very reason (http://erik.eae.net/archives/2005/06/06/22.13.54)
    various libraries provide their own hash-like implementations on top of Object (http://prototypejs.org/api/hash for example)- could you perhaps do something like that?


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •