What are js prototype and prototype chain
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('哈默', '前端开发') 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实例对象本身是没有teach()方法的,这时就会去teacher对象的__proto__隐式原型指向的Teacher.prototype显式原型上去找,此时找到了teach()方法并执行;同时,Teacher.prototype上仍然没有找到drink()方法,而Teacher.prototype也是一个对象,有自己的__proto__隐式原型,那么就去Teacher.prototype.__proto__上去找,Teacher.prototype.__proto__会指向Person()构造函数的显式原型Person.prototype,此时找到了drink()方法并执行,这就是原型链。
注:
(1)通过__proto__形成原型链而非protrotype。
(2)__proto__属性是对象所独有的。
(3)prototype属性是函数所独有的。但是由于JS中函数也是一种对象,所以函数也拥有__proto__属性。
三、判断对象自身是否有某属性或方法
hasOwnProperty()方法会返回一个布尔值,用于判断对象自身是否有某属性或方法。返回true,代表是该对象自身的属性或方法;返回false,代表是该对象原型上的属性或方法。
由于Person类继承自Object类,那么执行teacher.hasOwnProperty()方法时,实际会找到Object.prototype中的hasOwnProperty()方法并执行。
因此,所有继承了Object的对象都会继承到hasOwnProperty方法。
同时可以看到,Object.prototype.__proto__ 的值为 null ,即 Object.prototype 没有原型,所以可以想象在原型链中,当找到顶层原型还没有属性时,那就是没有这个属性,返回返回undefined。
instanceof 运算符:用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
看一个例子,使用typeof判断array的数据类型时,返回的是object,因此无法使用typeof判断array的类型。
const object = {}; const array = []; // 使用typeof判断数据类型,array返回的是object console.log(typeof object); // object console.log(typeof array); // object
下面使用instanceof运算符判断array的数据类型:
// 使用instanceof判断数据类型 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的原型链上,由此可以区分object和array的数据类型。
也可通过控制台查看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

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics



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.

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

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

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

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data