1. constructor
The value of constructor is a function. In JavaScript, values, arrays, functions and objects of types except null and undefined have a constructor attribute. The value of the constructor attribute is this value, array, function or object constructor. like:
Copy the code as follows: var a = 12, // Number
b = 'str', // String
c = false, // Boolean
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 constructors are built-in in JavaScript, and we can also customize constructors, such as:
The code copy is as follows:
function A(name) {
this.name = name;
}
var a = new A('a');
console.log(a.constructor); // A(name)
When calling the constructor, you need to use the new keyword. The constructor returns an object. You will know by looking at the following code:
The code copy is as follows: var a = 4;
var b = new Number(4);
console.log('a: ', typeof a); // a: number
console.log('b: ', typeof b); // b: object
2. 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 an anonymous function is called Object. like:
Copy the code as follows: function fn() {}
console.log(fn.prototype); // fn { }
Prototype attribute is mainly used to implement inheritance in JavaScript, such as:
Copy the 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
There is a problem here. The constructor of test is actually function A rather than function B:
Copy the code as follows: console.log(test.constructor); // A(name)
This is because B.prototype = A.prototype changed the constructor of B.prototype to A, so you need to restore the constructor of B.prototype:
Copy the 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 for doing this is because the value of prototype is an object, and its constructor function is the function where it is located, that is:
Copy the code as follows: console.log(A.prototype.constructor === A); // true