A value from which instances of a particular class are created. Every object that can be created by calling a constructor function has an associated prototype property.
Object
You can add new properties or methods to an existing class by adding them to the prototype associated with the constructor function for that class. The syntax for adding a new property or method is:
fun.prototype.name = value
If you add a new property to the prototype for an object, then all objects created with that object's constructor function will have that new property, even if the objects existed before you created the new property. For example, assume you have the following statements:
var array1 = new Array(); var array2 = new Array(3); Array.prototype.description=null; array1.description="Contains some stuff" array2.description="Contains other stuff"
After you set a property for the prototype, all subsequent objects created with Array will have the property:
The following example creates a method, str_rep, and uses the statement String.prototype.rep = str_rep to add the method to all String objects. All objects created with new String() then have that method, even objects already created. The example then creates an alternate method and adds that to one of the String objects using the statement s1.rep = fake_rep. The str_rep method of the remaining String objects is not altered.
var s1 = new String("a") var s2 = new String("b") var s3 = new String("c") // Create a repeat-string-N-times method for all String objects function str_rep(n) { var s = "", t = this.toString() while (--n >= 0) s += t return s } String.prototype.rep = str_rep // Display the results Console.Write("s1.rep(3) is " + s1.rep(3)) // "aaa" Console.Write("s2.rep(5) is " + s2.rep(5)) // "bbbbb" Console.Write("s3.rep(2) is " + s3.rep(2)) // "cc" // Create an alternate method and assign it to only one String variable function fake_rep(n) { return "repeat " + this + n + " times." } s1.rep = fake_rep Console.Write("s1.rep(1) is " + s1.rep(1)) // "repeat a 1 times." Console.Write("s2.rep(4) is " + s2.rep(4)) // "bbbb" Console.Write("s3.rep(6) is " + s3.rep(6)) // "cccccc"
This example produces the following output:
s1.rep(3) is aaa s2.rep(5) is bbbbb s3.rep(2) is cc s1.rep(1) is repeat a1 times. s2.rep(4) is bbbb s3.rep(6) is cccccc
The function in this example also works on String objects not created with the String constructor. The following code returns "zzz".
"z".rep(3)