js prototype and prototype chain are: 1. Prototype, all functions have a public and non-enumerable attribute like "prototype" by default, which will point to another object, which is the prototype. 2. Prototype chain. When accessing the properties or methods of an object, the object will first look for it from itself. If it cannot find it, it will look for it in the prototype, that is, in the "prototype" of its constructor. If it cannot be found in the prototype, , even if there is no such attribute in the constructor, it will look for it on the prototype behind the prototype, thus forming a chain structure called a prototype chain.
The operating system of this tutorial: windows10 system, JavaScript ECMAScript 2021 version, DELL G3 computer.
1. Prototype
Prototype: All functions have a public and non-enumerable attribute like "prototype" by default, which will point to another Object, this object is the prototype. Whenever an object (a function is also an object) is defined, a __proto__ attribute is generated, which is called the implicit prototype; this __proto__ attribute points to the prototype of the constructor of this object, which is called the explicit prototype. . Every object "inherits" properties from the prototype.
First look at an example, create a Student class, and create an instance object student of the class:
class Student{ constructor(name, score) { this.name = name; this.score = score; } introduce() { console.log(`我是${this.name},考了${this.score}分。`) } } const student = new Student('張三', 99) console.log('student', student); // student Student { name: '張三', score: 99} student.introduce(); // 我是張三,考了99分。
The console can access properties and methods.
But if you enter student directly on the console, you will find that there are only name and score attributes, no introduce method, but there is a [[Prototype]] attribute, using two square brackets bracketed.
Expand [[Prototype]], you will find that the introduce method is in [[Prototype]].
[[Prototype]] attribute is called the implicit prototype of the student object. When we want to find the properties or methods of an object, if we cannot find them on the current object, we will go to the implicit prototype [[Prototype]] attribute of the current object to find them.
The prototype can be accessed through the .__proto__ attribute. Note that there are two underscores on both sides of __proto__.
The Student() constructor also has a prototype attribute. The prototype attribute of the Student() constructor is actually equal to the __proto__ attribute of the student object.
The following is a picture to illustrate:
Therefore, the prototype attribute of the constructor is equal to the instance object's __proto__ attribute, the prototype attribute of the constructor is called the explicit prototype, and the __proto__ attribute of the instance object is called the implicit prototype.
2. Prototype chain
Prototype chain: When accessing the properties or methods of an object, first the object will look for it from itself. If it cannot be found, , it will look for it in the prototype, that is, __proto__, which is the prototype of its constructor; if it cannot be found in the prototype, that is, there is no such attribute in the constructor, because the constructor is also an object and also has __proto__, it will Look for the prototype, which forms a chain structure, called the prototype chain, which essentially describes an inheritance relationship of objects.
Let’s look at another example, create a Person class, create a Teacher class that inherits from the Person class, and create an instance object teacher:
class Person { constructor(name) { this.name = name; } drink(){ console.log('喝水'); } } class Teacher extends Person { constructor(name, subject) { super(name); this.subject = subject; } teach() { console.log(`我是${this.name}, 教${this.subject}。`) } } const teacher = new Teacher('哈默', '前端開發(fā)') console.log('teacher', teacher); teacher.teach(); teacher.drink();
The console output is as follows, and the teacher can execute it teach() and drink() methods.
Expand the teacher object and find that these two methods cannot be found, so I look for the prototype of the object, that is, the __proto__ attribute, find the teach() method, and then expand it. A layer of __proto__ attributes, find the drink() method.
The following is a picture to illustrate:
可以看到,teacher實(shí)例對(duì)象本身是沒有teach()方法的,這時(shí)就會(huì)去teacher對(duì)象的__proto__隱式原型指向的Teacher.prototype顯式原型上去找,此時(shí)找到了teach()方法并執(zhí)行;同時(shí),Teacher.prototype上仍然沒有找到drink()方法,而Teacher.prototype也是一個(gè)對(duì)象,有自己的__proto__隱式原型,那么就去Teacher.prototype.__proto__上去找,Teacher.prototype.__proto__會(huì)指向Person()構(gòu)造函數(shù)的顯式原型Person.prototype,此時(shí)找到了drink()方法并執(zhí)行,這就是原型鏈。
注:
(1)通過__proto__形成原型鏈而非protrotype。
(2)__proto__屬性是對(duì)象所獨(dú)有的。
(3)prototype屬性是函數(shù)所獨(dú)有的。但是由于JS中函數(shù)也是一種對(duì)象,所以函數(shù)也擁有__proto__屬性。
三、判斷對(duì)象自身是否有某屬性或方法
hasOwnProperty()方法會(huì)返回一個(gè)布爾值,用于判斷對(duì)象自身是否有某屬性或方法。返回true,代表是該對(duì)象自身的屬性或方法;返回false,代表是該對(duì)象原型上的屬性或方法。
由于Person類繼承自O(shè)bject類,那么執(zhí)行teacher.hasOwnProperty()方法時(shí),實(shí)際會(huì)找到Object.prototype中的hasOwnProperty()方法并執(zhí)行。
因此,所有繼承了Object的對(duì)象都會(huì)繼承到hasOwnProperty方法。
同時(shí)可以看到,Object.prototype.__proto__ 的值為 null ,即 Object.prototype 沒有原型,所以可以想象在原型鏈中,當(dāng)找到頂層原型還沒有屬性時(shí),那就是沒有這個(gè)屬性,返回返回undefined。
instanceof 運(yùn)算符:用于檢測(cè)構(gòu)造函數(shù)的 prototype 屬性是否出現(xiàn)在某個(gè)實(shí)例對(duì)象的原型鏈上。
看一個(gè)例子,使用typeof判斷array的數(shù)據(jù)類型時(shí),返回的是object,因此無(wú)法使用typeof判斷array的類型。
const object = {}; const array = []; // 使用typeof判斷數(shù)據(jù)類型,array返回的是object console.log(typeof object); // object console.log(typeof array); // object
下面使用instanceof運(yùn)算符判斷array的數(shù)據(jù)類型:
// 使用instanceof判斷數(shù)據(jù)類型 const flagObject = object instanceof Array; const flagArray = array instanceof Array; console.log(flagObject); // false console.log(flagArray); // true
object instanceof Array返回false,表示Array.prototype不在object的原型鏈上;array instanceof Array返回true,表示Array.prototype在array的原型鏈上,由此可以區(qū)分object和array的數(shù)據(jù)類型。
也可通過控制臺(tái)查看object和array的原型。
注:[] instanceof Object 為 true
The above is the detailed content of What are js prototype and prototype chain. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

JavaScript and WebSocket: Creating high-performance real-time data visualization With the rapid development of the Internet, real-time data visualization is becoming more and more important in many fields. Whether it is financial transactions, logistics and transportation, or industrial monitoring and other fields, the visualization of real-time data can help us better understand and analyze the data and make more informed decisions. In web development, JavaScript and WebSocket technologies are combined to achieve high-performance real-time data visualization. W

JavaScript and WebSocket: Building an efficient real-time search engine Introduction: With the development of the Internet, users have higher and higher requirements for real-time search engines. When searching with traditional search engines, users need to click the search button to get results. This method cannot meet users' needs for real-time search results. Therefore, using JavaScript and WebSocket technology to implement real-time search engines has become a hot topic. This article will introduce in detail the use of JavaScript

Overview of how to use WebSocket and JavaScript to implement an online electronic signature system: With the advent of the digital age, electronic signatures are widely used in various industries to replace traditional paper signatures. As a full-duplex communication protocol, WebSocket can perform real-time two-way data transmission with the server. Combined with JavaScript, an online electronic signature system can be implemented. This article will introduce how to use WebSocket and JavaScript to develop a simple online