[Detailed explanation of JavaScript prototype chain prototype]

1.What is JavaScript prototype chain

In JavaScript, every object has a prototype property, which points to another object. The pointed object also has its own prototype, and so on, ultimately forming a prototype chain. The top of the prototype chain is Object.prototype, which is the root prototype of all objects.

When we access a property of an object, if the object itself does not have this property, JavaScript will look up along the prototype chain until it finds a matching property or reaches the end of the prototype chain.

2. How the JavaScript prototype chain works

The working principle of the JavaScript prototype chain is very simple: when we access a property of an object, if the object itself does not have this property, then JavaScript will look up along the prototype chain. This process continues until a matching property is found or the end of the prototype chain is reached.

Here's a very simple example of how the prototype chain works:

// 定义一个人类构造函数
function Person(name, age) {
    this.name = name;
    this.age = age;
}

// 添加一个打招呼的方法
Person.prototype.greet = function() {
    console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);
};

// 创建一个人类实例
const person = new Person('John', 30);

// 访问person的name属性,输出"John"
console.log(person.name);

// 访问person的greet方法,输出"Hi, my name is John and I'm 30 years old."
person.greet();

In this example, we create a Person constructor and add a greet method to its prototype object. When we use the new keyword to create a person instance, it inherits the greet method on the prototype object of the Person constructor.

Because the person object itself does not have a greet method, JavaScript will look up the prototype chain until it finds a matching method.

3. Multiple ways to create objects

In JavaScript, we have many ways to create objects. Depending on how it is created, the prototype chain of a JavaScript object will be different.

1. Create objects using literals

The prototype of objects created using literals is Object.prototype, that is, all objects created by literals are instances of Object.

// 创建一个空对象 
const emptyObj = {};
// 创建一个带有属性和方法的对象 
const obj = {
    name: 'John',
    age: 30,
    greet() {
        console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);
    }
};

2. Create objects using constructor methods

The prototype of an object created using the constructor method is the prototype object (prototype) of the constructor function.

// 定义一个人类构造函数 
function Person(name, age) {
    this.name = name;
    this.age = age;
}
// 添加一个打招呼的方法 
Person.prototype.greet = function () {
    console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);
};
// 创建一个人类实例 
const person = new Person('John', 30);

In this example, we create a Person object using the constructor method. When we use the new keyword to create a person instance, it inherits the greet method on the prototype object of the Person constructor.

3. Create objects using Class method

The class keyword was introduced in ES6, making classes and inheritance in JavaScript easier to understand and use. Although the bottom layer is still based on the prototype chain mechanism, this syntactic sugar simplifies the creation process of objects and inheritance.

class Person {
    constructor(name, age) {
      this.name = name;
      this.age = age;
    }
  
    greet() {
      console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);
    }
  }
  
  const person = new Person('John', 30);

Objects created in Class mode are the same as objects created in constructor mode. Their prototype is the object pointed to by the prototype attribute of the Class constructor.

4. Modify prototype and inheritance

By modifying the prototype, we can realize the inheritance relationship between objects. When an object's prototype changes, its prototype chain changes accordingly. In this way, objects can inherit properties and methods from their prototype chain, enabling code reuse and extension.

// 定义一个动物类构造函数
function Animal(legs) {
    this.legs = legs;
}

// 添加一个移动的方法
Animal.prototype.move = function() {
    console.log('Moving...');
};

// 定义一个鸟类构造函数
function Bird(name, legs) {
    this.name = name;
    Animal.call(this, legs); // 调用父类构造函数,继承父类属性
}

// 继承父类方法
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;

// 添加一个飞行的方法
Bird.prototype.fly = function() {
    console.log('Flying...');
};

const bird = new Bird('Pigeon', 2);
console.log(bird.name); // Pigeon
console.log(bird.legs); // 2
bird.move(); // Moving...
bird.fly(); // Flying...

Here we define an Animal constructor, which has a move method. Then we defined a Bird constructor and inherited the prototype object of the Animal constructor through the Object.create method, thus realizing the inheritance of the move method. Finally we added a fly method and created a bird object.

5. Performance and optimization of JavaScript prototype chain

The operation of the prototype chain in JavaScript will bring certain performance overhead. When accessing a property, the search process needs to go step by step along the prototype chain until the property is found or the end of the prototype chain is reached. Therefore, a prototype chain structure that is too deep may lead to performance degradation. In order to optimize performance, the prototype chain of the object can be designed reasonably to avoid overly large and complex structures.

6.Extended content of JavaScript prototype chain

  • In-depth understanding of the implementation details of the prototype chain, including the use of [[Prototype]] properties, __proto__ properties and the Object.getPrototypeOf() method.
  • Introduce the application of prototype chain in functions and constructors, as well as the application of prototype chain in function prototype extension and method inheritance.
  • Discuss the relationship between the prototype chain and the scope chain, and explain why global variables can be accessed in the prototype object.
  • Discuss the application scenarios of the Object.create() method and the Object.setPrototypeOf() method in prototype chain operations.
  • Quote some excellent resources and articles, such as MDN documents, JavaScript authoritative guide, etc., for readers to learn in depth and further expand their knowledge.

Summarize

By in-depth understanding of the concept, working principle and application of JavaScript prototype chain, we can better understand the mechanism of JavaScript object-oriented programming. The prototype chain is not only the basis for inheritance and attribute lookup in JavaScript, but also helps us deeply understand the design ideas of the JavaScript language. By properly applying the prototype chain, we can create efficient and scalable front-end code.

Guess you like

Origin blog.csdn.net/zhaochen1127/article/details/133809486
Recommended