Prototype prototype
Important concepts
- Prototype is a property of the constructor
- Objects instantiated from the same constructor have the same Prototype property
- Constructor specification: Dynamic values, usually written inside constructors, are changed by passing arguments. Methods and constant values are written to the constructor’s Prototype and inherited by the instance.
function Car(args) {
this.name = args.name;
this.color = args.color;
};
Car.prototype = {
printMyCar : function (){
console.log(this.name + this.color); }};const car = new Car({name: 'Benz'.color: 'red'});
car.printMyCar(); // Benzred
Copy the code
The constructor construtor
- Constructor belongs to the prototype constructor and refers to the constructor itself.
function Car(name, age) {
this.name = name;
this.age = age;
}
console.log(Car.prototype);
Copy the code
- Constructor can be changed
function Tel() {}
function Car(name, age) {
this.name = name;
this.age = age;
}
Car.prototype.constructor = Tel;
console.log(Car.prototype);
Copy the code
Prototype __proto__
- __proto__ is a property generated when the object is instantiated and stored in this.
- __proto__ belongs to the instantiated object.
- __proto__ is a container that holds the prototype of its constructor by default.
function Car(name, color) { this.name = name; this.color = color; } Car.prototype = { print: function () { console.log(this.name + this.color); }}; const car = new Car('Benz', 'red'); console.log(car);Copy the code
- __proto__ can be changed.
function Tel(name, age) {
this.name = name;
this.age = age;
}
Tel.prototype = {
telPrint: function () {
console.log(this.name + this.age); }};function Car(name, color) {
this.name = name;
this.color = color;
}
Car.prototype = {
print: function () {
console.log(this.name + this.color); }};const car = new Car('Benz'.'red');
car.__proto__ = Tel.prototype;
car.telPrint(); // Benzundefined
Copy the code
QA
- Execute the following code, what does it output?
function Car() {}
Car.prototype.name = 'lily';
const car = new Car();
Car.prototype.name = 'lucy';
console.log(car.name); // lucy
Copy the code
- Execute the following code, what does it output?
function Car() {}
Car.prototype.name = 'lily';
const car = new Car();
Car.prototype = {
name: 'lucy'
};
console.log(car.name); // lily
console.log(car);
Copy the code