First, constructor
The value of the constructor is a function. In JavaScript, values, arrays, functions, and objects, except null and undefined, have a constructor property, and the value of the constructor property is the constructor of that value, array, function, or object. Such as:
Copy Code code 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 ()
All of the above constructors are built into JavaScript, and we can also customize constructors, such as:
Copy Code code 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, and the constructor returns an object, as you can see from the following code:
Copy Code code as follows:
var a = 4;
var B = new number (4);
Console.log (' A: ', typeof a); A:number
Console.log (' B: ', typeof B); B:object
Second, prototype
Prototype is a property of a function, by default, the value of a function's prototype property is an empty object with the same name as the function, and the prototype property of the anonymous function is named object. Such as:
Copy Code code as follows:
function fn () {}
Console.log (Fn.prototype); fn {}
The prototype property is primarily used to implement inheritance in JavaScript, such as:
Copy Code code 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's a question, the constructor of test is actually a function rather than B function:
Copy Code code as follows:
Console.log (Test.constructor); A (name)
This is because B.prototype = A.prototype changes the B.prototype constructor to a, so the B.prototype constructor needs to be restored:
Copy Code code 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)
The reason to do this is because the value of the prototype is an object, and its constructor is the value of its constructor property, which is its function, namely:
Copy Code code as follows:
Console.log (A.prototype.constructor = = A); True