This article describes the prototype attribute in JavaScript. This attribute is an important basis for understanding JavaScript classes and inheritance. We have used prototype property simulation class and inheritance implementation in Chapter 1. The prototype attribute is essentially a JavaScript Object. Each function has a default prototype attribute.
If this function is used to create a custom object, we call it a constructor. For example, the following simple scenario:
The Code is as follows:
// Constructor
Function Person (name ){
This. name = name;
}
// Define the prototype of Person. attributes in the prototype can be referenced by custom objects.
Person. prototype = {
GetName: function (){
Return this. name;
}
}
Var zhang = new Person ("ZhangSan ");
Console. log (zhang. getName (); // "ZhangSan"
As an analogy, we consider the data types in JavaScript, such as String, Number, Array, Object, and Date. We have reason to believe that these types are implemented as constructors in JavaScript, such:
The Code is as follows:
// Define the constructor of the array as a predefined type of JavaScript
Function Array (){
//...
}
// Initialize an array instance
Var arr1 = new Array (1, 56, 34, 12 );
// However, we prefer the following syntax definition:
Var arr2 = [1, 56, 34, 12];
At the same time, many methods for Array Operations (such as concat, join, and push) should also be defined in the prototype attribute.
In fact, all the inherent Data Types in JavaScript have the read-only prototype attribute (this is understandable: If you modify the prototype attribute of these types, but we can add our own extension method to it.
The Code is as follows:
// Extend a method for obtaining the minimum value to the Array of the inherent JavaScript type.
Array. prototype. min = function (){
Var min = this [0];
For (var I = 1; I <this. length; I ++ ){
If (this [I] <min ){
Min = this [I];
}
}
Return min;
};
// Call the min Method on any Array instance
Console. log ([1, 56, 34, 12]. min (); // 1
Note: There is a trap. After adding an extension method to the Array prototype, this extension method will also be recycled when the for-in loop Array is used.
The following code illustrates this (assuming that the min method has been extended to the Array prototype ):
The Code is as follows:
Var arr = [1, 56, 34, 12];
Var total = 0;
For (var I in arr ){
Total + = parseInt (arr [I], 10 );
}
Console. log (total); // NaN
The solution is also simple:
The Code is as follows:
Var arr = [1, 56, 34, 12];
Var total = 0;
For (var I in arr ){
If (arr. hasOwnProperty (I )){
Total + = parseInt (arr [I], 10 );
}
}
Console. log (total); // 103