Home Web Front-end JS Tutorial JavaScript study notes (9) Prototype in JavaScript and the inheritance method of the prototype chain_Basic knowledge

JavaScript study notes (9) Prototype in JavaScript and the inheritance method of the prototype chain_Basic knowledge

May 16, 2016 pm 06:08 PM
prototype prototype chain

When using object-oriented programming, the inheritance relationship between objects is naturally indispensable! The prototype is a very important way to implement JavaScript inheritance!
Let’s first look at the following code:

Copy code The code is as follows:

function person (name, age) {
this.name = name;
this.age = age;
}
person.prototype.getInfo = function() {
alert("My name is " this.name ", and I have " this.age " years old");
}
var zhangchen = new person("zhangchen", 23);
zhangchen.getInfo(); // output My name is zhangchen, and I have 23 years old;

From the running results, we can see that the zhangchen object created through the keyword new inherits the getInfo( defined through the prototype in person )method. Let's take a closer look at how the newly created zhangchen object inherits the attributes and methods of the person object.
Prototype: In object-oriented programming using JavaScript, prototype objects are a core concept. The name comes from the concept that objects in JavaScript are created as copies of existing instance (i.e. prototype) objects. Any properties and methods of this prototype object will appear as properties and methods of the object created from the prototype's constructor. We can say that these objects inherit properties and methods from their prototype. When creating the zhangchen object:
Copy code The code is as follows:

var zhangchen = new company( "zhangchen", 23);

The object referenced by zhangchen will inherit properties and methods from its prototype, which comes from the properties of the constructor (in this case, the function person).

In JavaScript, every function has an attribute called prototype, which is used to refer to the prototype object. This prototype object in turn has a property called constructor, which in turn refers to the function itself. This is a circular reference. The following figure better illustrates this circular relationship.

JavaScript study notes (9) Prototype in JavaScript and the inheritance method of the prototype chain_Basic knowledge

Figure 1 Circular relationship

Now, when creating an object with a function (person in the example above) via the new operator, the obtained object will inherit the properties of person.prototype. In the image above, you can see that the person.prototype object has a constructor property that refers back to the person function. This way, each person object (inherited from person.prototype) has a constructor property that refers back to the person function.

We can use the following code to verify whether this loop is correct:

Copy the code The code is as follows:

function person(name, age) {
this.name = name;
this.age = age;
}

person.prototype.getInfo = function() {
alert("My name is " this.name ", and I have " this.age " years old");
}
var zhangchen = new person("zhangchen", 23);
alert(zhangchen.constructor == person.prototype.constructor); //output true
alert(zhangchen.constructor == person); // output true
alert(person.prototype.isPrototypeOf(zhangchen)) ; //output true

Where does the call to the "isPrototypeOf()" method in the above code come from? Is it from person.prototype object? No, in fact, there are other methods called toString, toLocaleString, and valueOf in person.prototype and person instances, but none of them come from person.prototype. Rather, it comes from Object.prototype in JavaScript, which is the ultimate base prototype for all prototypes. (The prototype of Object.prototype is null.)

In the above example, zhangchen.prototype is the object. It is created by calling the Object constructor (although it is not visible) which is equivalent to executing the following code:
Copy code The code is as follows :

zhangchen.prototype = new Object();

So, just as person instances inherit person.prototype, zhangchen.prototype inherits Object.prototype. This causes all zhangchen instances to also inherit the methods and properties of Object.prototype.

Prototype Chain: Every JavaScript object inherits a prototype chain, and all prototypes terminate in Object.prototype. Note that this inheritance is between active objects. It differs from the common concept of inheritance, which refers to inheritance between classes that occurs when they are declared. Therefore, JavaScript inheritance is more dynamic. It achieves this using a simple algorithm as follows: When you try to access a property/method of an object, JavaScript checks whether the property/method is defined in that object. If not, the object's prototype is checked. If not, then the prototype of the object's prototype is checked, and so on, all the way to Object.prototype. The following figure illustrates this parsing process:

JavaScript study notes (9) Prototype in JavaScript and the inheritance method of the prototype chain_Basic knowledge
Figure 2 The parsing process of toString() method

From the above parsing process, if property/method X is defined in the object, the property/method with the same name will be hidden in the prototype of the object. For example, you can override the toString method of Object.prototype by defining the toString method in person.prototype.

Look at the following code again:

Copy the code The code is as follows:

function person(name , age) {
this.name = name;
this.age = age;
}
person.prototype.getInfo = function() {
alert("My name is " this .name ", and I have " this.age " years old");
}
var zhangchen = new person("zhangchen", 23);
var luomi = new person("luomi", 23);
zhangchen.getInfo(); // output My name is zhangchen, and I have 23 years old;
luomi.getInfo(); // output My name is luomi, and I have 23 years old ;
luomi.getInfo = function() {
alert("here can rewrite the function of getInfo!");
}
luomi.getInfo(); //here can rewrite the function of getInfo!
zhangchen.getInfo(); // output My name is zhangchen, and I have 23 years old;

As you can see from the running results, although each instance of person inherits methods in person.prototype, but we can also redefine methods in the prototype object in the instantiated object, and it will not affect other instances!

The above is my understanding of prototypes and prototype chain inheritance methods. Please refer to (JavaScript: Using Object-Oriented Technology to Create Advanced Web Applications). I hope everyone can discuss it together!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Introduction to the new map of Genshin Impact version 4.4 Introduction to the new map of Genshin Impact version 4.4 Jan 31, 2024 pm 06:36 PM

Introducing the new map of Genshin Impact version 4.4. Friends, Genshin Impact 4.4 version also ushered in the Sea Lantern Festival in Liyue. At the same time, a new map area will be launched in version 4.4 called Shen Yu Valley. According to the information provided, Shen Yugu is actually part of Qiaoying Village, but players are more accustomed to calling it Shen Yugu. Now let me introduce the new map to you. Introduction to the new map of Genshin Impact version 4.4. Version 4.4 will open "Chenyu Valley·Shanggu", "Chenyu Valley·Nanling" and "Laixin Mountain" in the north of Liyue. Teleportation anchor points have been opened for travelers in "Chenyu Valley·Shanggu" . ※After completing the prologue of the Demon God Quest·Act 3: The Dragon and the Song of Freedom, the teleportation anchor point will be automatically unlocked. 2. Qiaoyingzhuang When the warm spring breeze once again caressed the mountains and fields of Chenyu, the fragrant

What are prototypes and prototype chains What are prototypes and prototype chains Nov 09, 2023 pm 05:59 PM

Prototype, an object in js, is used to define the properties and methods of other objects. Each constructor has a prototype attribute. This attribute is a pointer pointing to a prototype object. When a new object is created, the new object will be The prototype attribute of its constructor inherits properties and methods. Prototype chain, when trying to access the properties of an object, js will first check whether the object has this property. If not, then js will turn to the prototype of the object. If the prototype object does not have this property, it will continue to look for the prototype of the prototype.

What is scope chain and prototype chain? What is scope chain and prototype chain? Nov 13, 2023 pm 01:46 PM

Scope chain and prototype chain are two important concepts in JavaScript, corresponding to the two core features of scope and inheritance respectively: 1. Scope chain is a mechanism used to manage variable access and scope in JavaScript. It is formed by It is determined by the execution context and lexical scope in which the function is created; 2. The prototype chain is a mechanism for implementing inheritance in JavaScript. Based on the prototype relationship between objects, when accessing the properties or methods of an object, if the object itself does not Definition, will be searched up along the prototype chain.

What is the difference between prototype and prototype chain What is the difference between prototype and prototype chain Nov 09, 2023 pm 04:48 PM

The difference between prototype and prototype chain is: 1. Prototype is an attribute that each object has, including some shared attributes and methods, which is used to realize the sharing and inheritance of attributes and methods between objects, while prototype chain is a The inheritance mechanism is implemented through the prototype relationship between objects, which defines the inheritance relationship between objects so that objects can share the properties and methods of the prototype object; 2. The function of the prototype is to define the shared properties and methods of the object, so that multiple Objects can share the properties and methods of the same prototype object, and the function of the prototype chain is to realize the inheritance relationship between objects, etc.

Performance comparison of Go language and Python: Which one is more suitable for high-performance programming? Performance comparison of Go language and Python: Which one is more suitable for high-performance programming? Jan 30, 2024 am 08:13 AM

Go language and Python are two very popular programming languages, both with their own advantages and characteristics. There are also some differences between the two when it comes to high-performance programming. This article will compare the Go language and Python to explore which one is more suitable for high-performance programming. First, let us understand the Go language. The Go language is an open source programming language developed by Google that focuses on simplicity, efficiency, and concurrency. One of the design goals of the Go language is to provide a high-performance programming experience. It has lightweight coroutines (goro

This domestic free programming tool is popular! Developed by a PhD team from Tsinghua University, it has short response delay and high accuracy. This domestic free programming tool is popular! Developed by a PhD team from Tsinghua University, it has short response delay and high accuracy. Jan 31, 2024 pm 05:03 PM

In the past year, with the widespread application of large model technology, we have witnessed how AI has profoundly changed the way we work. In the field of programming, the intervention of AI will also bring unprecedented convenience to programmers. Recently, Feishen Technology launched FittenCode, an AI code assistant based on a large self-developed code model. It can help programmers complete coding tasks more quickly, accurately, and with higher quality, greatly improve coding efficiency, and contribute to Free and open to users! The product’s official website address: https://code.fittentech.com/FittenCode has quickly become popular since its last release. The development team worked around the clock to bring features,

What is the purpose of prototypes and prototype chains? What is the purpose of prototypes and prototype chains? Jan 13, 2024 pm 12:58 PM

The reason why prototypes and prototype chains exist is to implement inheritance and sharing of object properties in the JavaScript language. In JavaScript, everything is an object, including functions. Every object has a property called a prototype that points to another object, which is called a prototype object. Objects can inherit properties and methods from prototype objects. The benefit of implementing shared properties and methods through prototypes is memory savings. Consider an object A, which has some properties and methods, then create object B and make

Choose the right programming language: Compare Go and Python to determine the best choice for your project needs Choose the right programming language: Compare Go and Python to determine the best choice for your project needs Jan 30, 2024 am 08:00 AM

In today's era of rapid technological advancement, the choice of programming language has become very critical. With the continuous development of the software development field, Go language and Python have become two programming languages ​​that have attracted much attention. This article will conduct a comparative analysis of Go language and Python to help readers choose the appropriate programming language according to project needs. First, let us understand the Go language. Go language is a statically compiled programming language developed by Google. It has powerful concurrent processing capabilities and efficient garbage collection mechanism, which is very

See all articles