In-depth understanding of JavaScript prototype chain and inheritance mechanism

JavaScript is a flexible and powerful programming language, and its unique prototype chain and inheritance mechanism are one of its core features. In this article, we will delve into the prototype chain and inheritance mechanism in JavaScript to help readers better understand this important concept.


What is the prototype chain?

In JavaScript, every object has a reference that links internally to another object, called a prototype. Prototype objects can contain properties and methods, and other objects can inherit these properties and methods. When we access a property or method of an object, JavaScript will first look in the object itself, and if it cannot find it, it will look up the prototype chain until it finds the property or method or reaches the top of the prototype chain.

In the above mentioned code, we defined two classes Personand Student, and extendscreated Studenta subclass of the class using the keyword Teacher. We can implement method inheritance through the prototype chain to ensure that subclasses can access the methods of the parent class.

Create the object's prototype chain

Every JavaScript object has a built-in property __proto__that points to the prototype object of the constructor that created the object. This link is the key to the prototype chain. Let's understand this with an example:

function Animal() {}
const dog = new Animal();

console.log(dog.__proto__); // 输出:Animal {}
console.log(Animal.prototype); // 输出:Animal {}
console.log(dog.__proto__ === Animal.prototype); // 输出:true

In the above example, we created an empty Animalconstructor and then newcreated an dogobject named using the keyword. dog.__proto__Pointed to Animal.prototype, so that the properties and methods on it dogcan be inherited .Animal.prototype

Prototype chain inheritance and method rewriting

In JavaScript, subclasses can inherit the methods of the parent class, and can also override the inherited methods. Let us illustrate with the code example given above:

class Person{
  constructor(name) {
    this.name=name;
  }
  introduce(){
    console.log(`Hello, I am ${this.name}`);
  }
  drink(){
    console.log('I am drinking');
  }
}
class Student extends Person{
  constructor(name,score) {
    super(name)
    this.score= score;
  }
  introduce(){
    console.log(`Hello, I am ${this.name}.and ${this.score}is my score`);
  }
}
const student =new Student('John', 100);
student.introduce();
class Teacher extends Person{
  constructor(name,subject){
    super(name)
    this.subject=subject;
  }
  introduce(){
    console.log(`Hello, I am ${this.name}.and ${this.subject}is my subject`);
  }
}
const teacher =new Teacher('John', 'Math');
teacher.introduce();
console.log(student)
teacher.drink();

In the above example, Studentthe class inherits Personthe class and overrides introduce()the method. When we call student.introduce(), it executes the method Studentin the class introduce(), not Personthe method in the class.


Inheritance and the super keyword

In subclasses, we can use superkeywords to call constructors and methods of superclasses. This keeps subclasses related to their parent classes and adds extra functionality to subclasses. Let's continue the example above, Teacheradding a new method to the class and calling the superclass's constructor:

In the above example, by super(name)calling Personthe constructor, we ensure that Teacherthe constructor of the parent class is also called for initialization when the class is instantiated.

class Teacher extends Person {
  constructor(name, subject) {
    super(name);
    this.subject = subject;
  }

  introduce() {
    console.log(`Hello, I am ${this.name}. and ${this.subject} is my subject`);
  }

  teach() {
    console.log('I am teaching');
  }
}

const teacher = new Teacher('John', 'Math');
teacher.introduce(); // 输出:Hello, I am John. and Math is my subject
teacher.teach(); // 输出:I am teaching

Summarize

JavaScript's prototype chain and inheritance mechanism is one of its powerful features. Through the prototype chain, objects can inherit the properties and methods of other objects to realize code reuse and organization. In subclasses, we can extendsinherit the parent class through keywords, and use superkeywords to call the constructors and methods of the parent class. This way, we can create more flexible and extensible code structures.

I hope this article helps you understand JavaScript's prototype chain and inheritance mechanism. A solid understanding of this concept will make you more comfortable writing JavaScript code. Happy coding!

Guess you like

Origin blog.csdn.net/weixin_60895836/article/details/131900331