Each object has a hidden object attribute that is used to point to its parent object (a function for constructing the object). This is called a parent object or an implicit object ), and inherit from its attributes and methods [function object has an explicit prototype reference in addition to the parent prototype reference]. In general, the parent prototype of the image cannot be accessed, and the explicit prototype of the function object can be accessed through FunctionName. prototype access [in FireFox, you can access the parent prototype of the object through the _ proto _ attribute of the object]
This prototype property is an Object-type Object. Therefore, you can add any attributes and methods to this prototype property so that the instance Object can inherit them.
For example, the prototype of a String-type object is String. prototype. If we want to add some custom methods to the String-type object, we can do this (here we will add a trim method in the class VBscript as an example)
Copy codeThe Code is as follows:
String. prototype. trim = function (){
Return this. replace (/^ \ s * | \ s * $/g ,"")
}
// "Jiangsk540". trim (); // return "jiagnsk540"
In addition to the above features, the prototype also provides a mechanism for sharing attributes and methods of a group of similar instances [equivalent to static attributes or static functions, no matter how many instance images are created using the constructor, the attributes and methods defined on the prototype are defined only once from start to end, all instance peers share the concept of using this property or method, but it is not the same as the static property or static function of C ++ or JAVA]
Copy codeThe Code is as follows:
Function Class1 (name ){
This. name = name;
}
Class1.prototype. show = function (){
Alert ("name =" + this. name );
}
Var m1 = new Class1 ("jiangsk540 ");
Var m2 = new Class1 ("Mao Lions ");
Alert (m1.show === m2.show); // display true
The attributes or methods dynamically added to the constructor prototype can be called immediately by the previously created object.
For example
Copy codeThe Code is as follows:
Function Class1 (name ){
This. name = name;
}
Class1.prototype. show = function (){
Alert ("name =" + this. name );
}
Var m1 = new Class1 ("jiangsk540 ");
Class1.prototype. say = function (){
Alert ("Hi ");
}
M1.say () // call successful
/*
Note: Only the attributes or methods added to the constructor's prototype can be called immediately by the created object.
If it is a reference to change the constructor prototype, the created object cannot be called immediately.
*/
Class1.prototype = {newP: "jiangsk540 "};
Alert (m1.newP) // undefined