1. constructor
The constructor value is a function. In JavaScript, all types of values, arrays, functions, and objects except null and undefined have a constructor attribute, the value of the constructor attribute is the value, array, function, or object constructor. For example:
Copy codeThe Code is as follows: var a = 12, // number
B = 'str', // string
C = false, // Boolean Value
D = [1, 'D', function () {return 5 ;}], // Array
E = {name: 'E'}, // object
F = function () {return 'function';}; // function
Console. log ('a: ', a. constructor); // Number ()
Console. log ('B:', B. constructor); // String ()
Console. log ('C: ', c. constructor); // Boolean ()
Console. log ('d: ', d. constructor); // Array ()
Console. log ('e: ', e. constructor); // Object ()
Console. log ('f: ', f. constructor); // Function ()
The above constructor is built in JavaScript, and we can also customize the constructor, such:
Copy codeThe Code is as follows:
Function A (name ){
This. name = name;
}
Var a = new A ('A ');
Console. log (a. constructor); // A (name)
When calling a constructor, you need to use the new keyword. The constructor returns an object. You can see the following code:
Copy codeCode: var a = 4;
Var B = new Number (4 );
Console. log ('a: ', typeof a); // a: number
Console. log ('B:', typeof B); // B: object
Ii. prototype
Prototype is a function attribute. By default, the prototype attribute value of a function is an empty Object with the same name as the function. The prototype attribute of an anonymous function is named Object. For example:
Copy codeThe Code is as follows: function fn (){}
Console. log (fn. prototype); // fn {}
The prototype attribute is mainly used to implement inheritance in JavaScript, such:
Copy codeThe Code is as follows: function A (name ){
This. name = name;
}
A. prototype. show = function (){
Console. log (this. name );
};
Function B (name ){
This. name = name;
}
B. prototype = A. prototype;
Var test = new B ('test ');
Test. show (); // test
Here is A problem. The test constructor is actually A function rather than B function:
Copy codeThe Code is as follows: console. log (test. constructor); // A (name)
This is because B. prototype = A. prototype changes the constructor B. prototype to A, so we need to restore the constructor B. prototype:
Copy codeThe Code is as follows: function A (name ){
This. name = name;
}
A. prototype. show = function (){
Console. log (this. name );
};
Function B (name ){
This. name = name;
}
B. prototype = A. prototype;
B. prototype. constructor = B;
Var test = new B ('test ');
Test. show (); // test
Console. log (test. constructor); // B (name)
This is because the prototype value is an object, and its constructor attribute value is its function, that is:
Copy codeThe Code is as follows: console. log (A. prototype. constructor = A); // true