Using Javascript array objects.

Add common properties for Array object instances.

The prototype object.

  • The Array object have a prototype property which is a reference to an object that contains common properties for all object instances you creates out of the Array object.
  • All created array object instances has a hidden reference to this prototype object, but you don't need to use that. You can access the common properties directly through the array object instance variable.
  • You must use the keyword 'this', which is a reference to the object you have created out of an Array object, to get access to all the common properties.

Create common properties for all array instances.

  • There are two main ways to add new common properties for all array instances:
    1. Add a property to the prototype property using the Array constructor.


      Example:
      <script type="text/javascript">
      var arr =[3,4,5,62];
      // summary is a property that has a value of a function
        Array.prototype.summary=function(initial) {
          var sum=initial;
          for (var s=0 ; s<this.length; s++) {
            sum+=this[s];
          }
          return sum;
        }
        // summary is a new method for all instances of arrays
        document.write("array sum: "+arr.summary(0)+"<br>");
        arr =["I"," love"," my"," baby!"];
        document.write("array sum: "+arr.summary("")+"<br>");
      </script>
    2. Add a property to the prototype property using a created array object instance.

      A created array object has a property, constructor, that refer back to the constructor name of the object.

      To do it this way we use the property, prototype, on that constructor:

      Example:
      <script type="text/javascript">
      var arr =[3,4,5,62];
      // summary is a property that has a value of a function
        arr.constructor.prototype.summary=function(initial) {
          var sum=initial;
          for (var s=0 ; s<this.length; s++) {
            sum+=this[s];
          }
          return sum;
        }
        // summary is a new method for all instances of arrays
        document.write("array sum: "+arr.summary(0)+"<br>");
        arr =["I"," love"," my"," baby!"];
        document.write("array sum: "+arr.summary("")+"<br>");
      </script>

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.