Function.prototype

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.

Property of Function

Description

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
where

fun The name of the constructor function object you want to change.
name The name of the property or method to be created.
value The value initially assigned to the new property or method.

If you add a 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:

After you set a property for the prototype, all subsequent objects created with Array will have the property:

Example

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.

The function in this example also works on String objects not created with the String constructor. The following code returns "zzz".

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.