1. Constructor
The value of constructor is a function. In JavaScript, values, arrays, functions, and objects of types other than null and undefined have a constructor attribute. The value of the constructor attribute is the constructor of the value, array, function, or object. For example:
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 constructors are all built-in in JavaScript. We can also customize the constructors, such as:
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 can see it by looking at the following code:
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 an attribute of a function. By default, the value of the prototype attribute 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:
function fn() {}
console .log(fn.prototype); // fn { }
The
prototype attribute is mainly used to implement inheritance in JavaScript, such as:
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 instead of function B:
console.log(test.constructor); // A(name)
This is because B.prototype = A.prototype changes the constructor of B.prototype to A, so the constructor of B.prototype needs to be restored:
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 why we do this is because the value of prototype is an object, and its constructor, that is, the value of its constructor attribute is the function it is in, that is:
console.log(A.prototype.constructor === A); // true