Array.prototype.nature = "Vegetable"
Onions = new Array(2)
Peppers = new Array(2)
Pork = new Array(2)
Salt = new Array(2)
Pork.nature = "Animal"
Salt.nature = "Mineral"
document.write("<P><B>What is the nature of Onions?</B>") document.write("<P>") document.write(Onions.nature)
document.write("<P><B>What is the nature of Peppers?</B>") document.write("<P>") document.write(Peppers.nature)
document.write("<P><B>What is the nature of Pork?</B>") document.write("<P>") document.write(Pork.nature)
document.write("<P><B>What is the nature of Salt?</B>") document.write("<P>") document.write(Salt.nature)
Of course - this will print the "Vegetable", "Animal", and "Mineral" natures.
</SCRIPT>
This is just a prototype, you understand.
The key line in this program is:
Array.prototype.nature = "Vegetable"
This line tells the JavaScript interpreter that any array declared in this program has an additional property called array.nature and, by default, the array.nature property is equal to Vegetable. Later, this program assigns other values to the various arrays' nature properties with statements like this one:
Salt.nature = "Mineral"
It then goes on to refer to the arrays' nature properties with statements such as:
document.write(Salt.nature)
The prototype property that's part of most JavaScript objects allows us to extend objects, adding additional properties and methods to them, as we require. This helps make our code more compact and easier to read.
Let's say we have a function that returns true when an array sent to it contains at least one element that's not evenly divisible by zero. We want to make this a supplementary method -- the containsOdd() method -- of the standard Array object. Here is the function:
function containsOdd() {
for (var i = 1; i < this.length; i++)
{
if ((this[i] % 2) != 0) return true
}
return false
}
The only thing unusual about that function is that it obviously operates on an Array object, but there's no parameter specified in the parenthesis on the first line. A parameter is not required because it employs the "this" keyword. You'll see how that works in a second.
To attach that function to Array as a method, we have to invoke the prototype property. Essentially, prototype means "the object as it is," and implies that we can stick additional methods and properties to the existing definition. The syntax for doing that is as follows:
Array.prototype.containsOdd = containsOdd; ------ So, now that method "containsOdd" is a method for our arrays.
Now, assuming that oddArray is an array that contains at least one odd element, this code...
flag = oddArray.containsOdd();
...will leave flag set to true.