We have already used the prototype attribute in Chapter 1 to simulate the implementation of classes and inheritance. The prototype property is essentially a JavaScript object. And every function has a default prototype attribute.
If this function is used in the scenario of creating a custom object, we call this function a constructor. For example, a simple scenario below:
//Constructor
function Person(name) {
this.name = name;
}
// Define the prototype of Person. The 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, let's consider the data types in JavaScript - String, Number, Array, Object, Date (Date) etc. We have reason to believe that these types are implemented as constructors inside JavaScript, such as:
// Define the constructor of the array, as a predefined type of JavaScript
function Array() {
// ...
}
// Instance of initializing array
var arr1 = new Array(1, 56, 34, 12);
// However, we prefer the following syntax definition:
var arr2 = [1, 56, 34 , 12];
Many methods of operating on arrays at the same time (such as concat, join, push) should also be defined in the prototype attribute.
In fact, all intrinsic data types of JavaScript have read-only prototype attributes (this is understandable: because if the prototype attributes of these types are modified, the predefined methods disappear), but we can Add your own extension methods to it.
//Extend one to the JavaScript inherent type Array to get the minimum value Method of
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;
};
// on any instance of Array Call the min method
console.log([1, 56, 34, 12].min()); // 1
Note: There is a trap here, add it to the prototype of Array After the extension method, when using for-in to loop the array, this extension method will also be looped out.
The following code illustrates this (assuming that the min method has been extended to the Array prototype):
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 very simple:
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