Simple summary of a prototype and constructor in JavaScript
- 2020-03-30 02:34:13
- OfStack
A constructor,
The value of the constructor is a function. In JavaScript, values of types other than null and undefined, arrays, functions, and objects, all have a constructor attribute whose value is the constructor of the value, array, function, or object. Such as:
var a = 12, // digital
b = 'str', //string
c = false, //Boolean value
d = [1, 'd', function() { return 5; }], // An array of
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 constructor, such as:
function A(name) {
this.name = name;
}
var a = new A('a');
console.log(a.constructor); // A(name)
When calling the constructor, the new keyword is needed. The constructor returns an object. See 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
Second, the 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. Such as:
function fn() {}
console.log(fn.prototype); // fn { }
The prototype property 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
The problem here is that the constructor for test is actually A, not B:
console.log(test.constructor); // A(name)
This is because b.pdtotype = a.pdtotype changes the constructor of b.pdtotype to A, so the constructor of b.pdtotype 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 for this is that the value of prototype is an object, and its constructor, the value of its constructor property, is its function.
console.log(A.prototype.constructor === A); // true