We have used the prototype property in the first chapter to simulate the implementation of classes and inheritance. The prototype property is essentially a JavaScript object. And each function has a default prototype property.
If this function is used in a scene that creates a custom object, we call this function a constructor. For example, here's a simple scenario:
Copy Code code as follows:
Constructors
function person (name) {
THIS.name = name;
}
Defines the prototype of person, in which attributes 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, consider the data types in JavaScript-strings, numbers, arrays (array), objects (object), dates (date), and so on. We have reason to believe that these types are implemented as constructors within JavaScript, such as:
Copy Code code as follows:
Defines the constructor of an array as a predefined type of javascript
function Array () {
// ...
}
Initializing an instance of an array
var arr1 = new Array (1, 56, 34, 12);
However, we prefer the following syntax definition:
var arr2 = [1, 56, 34, 12];
Many of the methods (such as Concat, join, push) of an array operation should also be defined in the prototype attribute.
In fact, all of the intrinsic data types of JavaScript have read-only prototype attributes (this is understandable: because if these types of prototype properties are modified, which predefined methods disappear), we can add our own extension methods to them.
Copy Code code as follows:
Extending a method of obtaining the minimum value to the JavaScript intrinsic type array
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 an instance of any array
Console.log ([1, 12].min ()); 1
Note: There is a trap to add an extension method to the array's prototype, and the extension method is also 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's prototype):
Copy Code code 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:
Copy Code code 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