SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    May 2004
    Location
    Quebec, Canada
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Extending Arrays with properties via prototype

    Hi!
    I'm trying out to extend the Arrays in JS with new properties via prototype. Not sure where to go with this though.

    I'd like to have new arrays created to have 3 properties that could be accessed by an array item. Something like this :

    myArray = new Array();
    myArray[0].property1 = 'something';
    myArray[0].property2 = 'something else';
    myArray[0].property3 = 'something else again';

    Is this possible? I've fiddled around with things like :
    Array.prototype.property1 = '';
    Array.prototype.property2 = '';
    Array.prototype.property3 = '';

    ... and the creating an array but I get myArray[0] has no properties (in Firefox 2). Am I doing this right? Thank you!

  2. #2
    SitePoint Evangelist bals28mjk's Avatar
    Join Date
    Aug 2007
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Nah, you need to create a constructor function and create a new instance of that object e.g
    Code:
    function types(name,size)
    {
    	this.name=name
    	this.size=size
    	this.msg=function(){alert("name:"+this.name+" size:"+this.size)}
    	
    }
    
    alert('hi')
    var animals=new Array()
    animals[0]=new types("frog","small")
    animals[0].msg()
    Adding a prototype will create a unversial property for all the objects in that instance.

  3. #3
    SitePoint Zealot
    Join Date
    May 2004
    Location
    Quebec, Canada
    Posts
    101
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Works great, thanks!

  4. #4
    SitePoint Evangelist bals28mjk's Avatar
    Join Date
    Aug 2007
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Your welcome .


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
  •