We use the prototype attribute to provide a set of basic functions of the object class. In addition, the new instance "inherit" of the object grants the operation of the object prototype. But how is this prototype implemented and managed?
For the description of the prototype attribute of an object, the JScript manual says that all internal JScript objects have the read-only prototype attribute. You can dynamically add features (attributes and methods) to the prototype, but the object cannot be assigned different prototypes. However, user-defined objects can be assigned to new prototypes.
The following shows three examples of using the classic prototype attribute.
1. Add methods for built-in objects in the script environment:
Copy codeThe Code is as follows:
Array. prototype. max = function ()
{
Var I, max = this [0];
For (I = 1; I <this. length; I ++)
{
If (max <this [I])
Max = this [I];
}
Return max;
};
2. Add methods for user-defined classes:
Copy codeThe Code is as follows:
Function TestObject (name)
{
This. m_Name = name;
}
TestObject. prototype. ShowName = function ()
{
Alert (this. m_Name );
};
3. Update the prototype of the custom class:
Copy codeThe Code is as follows:
Function TestObjectA ()
{
This. MethodA = function ()
{
Alert ('testobjecta. MethodA ()');
}
}
Function TestObjectB ()
{
This. MethodB = function ()
{
Alert ('testobjectb. MethodB ()');
}
}
TestObjectB. prototype = new TestObjectA ();
Third, are you familiar with it? Yes, it is the prototype inheritance method we introduced earlier ~~ However, today we are not studying "inheritance". The reason why we can implement a kind of inheritance is to take advantage of a side effect of the prototype attribute.
Prototype also has a default attribute: constructor, which is used to represent the function for creating objects (that is, the constructor mentioned in OOP ). The constructor attribute is a member of all objects with the prototype attribute. They include all internal JScript objects except Global and Math objects. The constructor attribute stores references to the functions used to construct a specific object instance.
After figuring out how to use the prototype attribute in JScript, we will study it in depth.