We use the prototype property to provide a set of basic functions for the object's class. And a new instance of the object "inherits" the action given to the object's prototype. But how exactly is this prototype implemented and managed?
For a description of the object's prototype property, the JScript manual says: All JScript internal objects have read-only prototype properties. You can dynamically add functionality (properties and methods) to its prototype, but the object cannot be assigned a different prototype. However, user-defined objects can be assigned to a new prototype.
Let's look at three examples of the use of classic prototype properties.
1. Add methods for building objects in script environment:
Copy Code code 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 Code code 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 Code code as follows:
function Testobjecta ()
{
This. MethodA = function ()
{
Alert (' Testobjecta.methoda () ');
}
}
function TESTOBJECTB ()
{
This. MethodB = function ()
{
Alert (' Testobjectb.methodb () ');
}
}
Testobjectb.prototype = new Testobjecta ();
The third one looks familiar, doesn't it? Yes, it is the prototype inheritance method we introduced earlier ~ ~ But today we are not studying "inheritance", the reason why we can implement a kind of inheritance, just take advantage of a side effect of the prototype attribute.
Prototype also has a default attribute: constructor, which is used to represent the function that created the object (that is, the constructor in our OOP). The constructor property is a member of all objects that have prototype properties. They include all JScript internal objects except the global and math objects. The constructor property holds a reference to a function that constructs a particular object instance.
After figuring out how to use the prototype attribute in JScript, let's look at it in depth.
Current 1/2 page
12 Next read the full text