The prototype property

The prototype property allows you to add properties and methods to an object that already exists, in our case an Array object.

Array.prototype.NewProperty = DefaultValue;

The NewProperty will be replaced with the name you want to use for the new property and the DefaulValue with the default value you want that property to have.

Array.prototype.attitude = "amazing";
var StudentsClass = new Array();
document.write("This class is "+StudentsClass.attitude);

The output will be “This class is amazing”.

The addition of a new property like this affects every array in the document afterward. If you want to use prototype property with two arrays on the page and the first array to print on the page the default value while the second array to print a new value then you might use something like this:

Array.prototype.attitude = "amazing";
var StudentsClass = new Array();
document.write("This class is "+StudentsClass.attitude);

var AnotherClass = new Array();
AnotherClass.attitude = "not so amazing";
document.write("The class next to it is "+AnotherClass.attitude);

As you can see, the second array uses the attitude property but it doesn’t keep it’s value, it changes it to “not so amazing”.

Leave a Reply