Table of Contents
1. Prototype
1. Concept
4.原型链关系内存图
Home Web Front-end JS Tutorial Detailed explanation of JavaScript prototype and prototype chain knowledge points

Detailed explanation of JavaScript prototype and prototype chain knowledge points

Jul 06, 2022 pm 01:44 PM
javascript

This article brings you relevant knowledge about javascript, which mainly organizes issues related to prototypes and prototype chains, including the concept of prototypes, the constructor attribute on function prototypes, and the prototype chain Understanding and so on, let’s take a look at it below, I hope it will be helpful to everyone.

Detailed explanation of JavaScript prototype and prototype chain knowledge points

[Related recommendations: javascript video tutorial, web front-end

1. Prototype

1. Concept

In JavaScript, a function is an object of type Function that contains properties and methods. The prototype (Prototype) is an attribute of the Function type object.

The prototype attribute is included when the function is defined, and its initial value is an empty object. There is no prototype type defined for functions in JavaScript, so the prototype can be of any type.

The prototype is used to save the shared properties and methods of the object. The properties and methods of the prototype do not affect the properties and methods of the function itself.

// Function类型的属性->所有函数都具有的属性
console.log(Function.prototype);//[Function]

// 定义函数
function fn() {
    console.log('this is function');
}

//原型的默认值是空对象
console.log(fn.prototype);//fn {}

// 函数包含构造函数 ——> 所有引用类型其实都是构造函数
console.log(Number.prototype); //[Number: 0]

console.log(Object.prototype);//{}
Copy after login

2. Get the prototype

You can get the prototype of the object in the following two ways to set shared properties and methods:

    Through the
  • prototype attribute of the constructor
  • Through the
  • getPrototype(obj) method of the Object object.
function fn() {
    console.log('this is function');
}

//使用访问对象的属性语法结构
console.log(fn.prototype);//fn {}
console.log(fn['prototype']);//fn {}

//Object类型提供getPrototypeOf()方法
console.log(Object.getPrototypeOf(fn));//[Function]
Copy after login

#3. Understand the constructor attribute on the function prototype

Object.getOwnPropertyDescriptors() The method is used to get a Descriptors for all of the object's own properties.

var result = Object.getOwnPropertyDescriptor(Object.prototype,'constructor');
console.log(result) //输出结果如下:
//{
//   value: [Function: Object],
//   writable: true,
//   enumerable: false,
//   configurable: true
// }
Copy after login

The constructor is automatically added when the function is created, pointing to the constructor itself

4. Set the properties and methods on the prototype

The properties and methods of the prototype can be set in the following two ways:

    The properties and methods of the prototype are defined separately.
构造函数.prototype.属性名 = 属性值 ;构造函数.prototype.方法名 = function(){} ;
Copy after login
    Define a new object directly for the prototype.
When we need to add many attributes to the prototype, it is too troublesome to write over and over again

Constructor.prototype.Attribute name, you can directly modify the entire prototype

构造函数.prototype = {
    属性名:属性值,
    方法名:function(){}}
Copy after login
function foo () {}foo.prototype = {
    constructor: foo,
    name: 'jam',
    age: 18,
    address: '北京市'}var fn = new foo()console.log(fn.address) // 北京市
Copy after login
5.isPrototypeOf() method

Every object will have a

isPrototypeOf() method, which uses To determine whether an object is the prototype of another object.

示例代码如下:
// 通过初始化器方式定义对象
var obj = {
    name:'jam'
}
// 定义构造函数
function Hero() {}
// 将对象obj赋值给构造函数Hero的原型
Hero.prototype = obj;
// 通过构造函数创建对象
var hero = new Hero();

// isPrototypeOf()方法判断指定对象是否是另一个对象的原型
var result = obj.isPrototypeOf(hero);
console.log(result);//true
Copy after login
Verified that the

obj object is the prototype of the hero object

2. Prototype chain

1. Understanding of the prototype chain

Next we use a piece of code to expand our understanding of the prototype chain:

场景:查找obj对象身上的address属性
js执行的步骤:
    1. 会触发get操作
    2. 在当前的对象中查找属性
    3. 如果没有找到,这个时候会去原型链(__proto__)对象上查找
       1. 查找到结束
       2. 没查找到一直顺着原型链查找,直到查找到顶层原型(顶层原型是什么暂时卖个关子)
Copy after login
1.1 The sample code is as follows:

var obj = {
    name: 'jam',
    age: 19
}
/* 
    要求:查找obj对象身上的address属性
*/

// 原型链一层一层向上查找,如果一直没有找到,直到查找到顶层原型结束
obj.__proto__ = {}
obj.__proto__.__proto__ = {}
obj.__proto__.__proto__.__proto__ = {
    address: '北京市'
}

console.log(obj.address) // 北京市
console.log(obj.__proto__.__proto__.__proto__)  // { address: '北京市' }
Copy after login

1.2 Memory graph

Detailed explanation of JavaScript prototype and prototype chain knowledge points

Finally find the address attribute


Then there is a problem here. If it is not found, it will go endlessly. Looking for it? Next, let’s take a look at

#2. What is the top-level prototype?

As we mentioned above, we will not search endlessly along the prototype chain. When the top-level prototype is found, if it has not been found yet,

undefined will be returned.

So what is the top-level prototype? The sample code is as follows:

var obj = { name: 'jam' }console.log(obj.__proto__)  // {}console.log(obj.__proto__.__proto__)  // null
Copy after login
The prototype of the literal object obj is:

{}. {} is the top-level prototype When we continue to print
__proto__, a null value is returned, which proves that the upper layer is already the top-level prototype

The following figure is a supplement to the top-level prototype that is missing in the first piece of code:


Detailed explanation of JavaScript prototype and prototype chain knowledge points

The top-level prototype is Object.prototype

3.Object's prototype (Object.prototype)

3.1 So where is the end of the prototype chain? For example, does the third object also have the prototype__proto__ attribute?

var obj = {name:'jam'}obj.__proto__ = {}obj.__proto__.__proto__ = {}obj.__proto__.__proto__.__proto__ = {}console.log(obj.__proto__.__proto__.__proto__.__proto__)  // {}
Copy after login
We found that the above printed result is

empty object {}

    In fact, this prototype is our top-level prototype
var obj = {
  name: 'jam',
  age: 19
  }
  console.log(obj.__proto__)  // {}
  console.log(Object.prototype) // {}
  console.log(obj.__proto__ === Object.prototype) // true
Copy after login
  • Object is the parent class of all classes

    So obj.__proto__ is actually Object.prototype,

    console.log(obj.__proto__ === Object.prototype) // true We can see that the result Object.prototype is the top-level prototype

  • The prototypes of objects created directly from Object are
  • {}
  • 3.2 Then we may ask: {}What is special about the prototype?

    • 特殊点1:该对象有原型属性,但是它的原型属性已经指向的是null,也就是已经是顶层原型了;
      console.log(obj.__proto__.__proto__.__proto__.__proto__.__proto__) // null
      Copy after login
    • 特殊点2:该对象上有甚很多默认的属性和方法;
      • 虽然打印Object.prototype的结果为空对象{},但它不是空的,只是里面的属性不可枚举而已,例如我们就打印constructor属性看看
        <!-- 可以看出是有constructor属性的 ,并不是空的-->console.log(Object.prototype.constructor)  // [Function: Object]  <!-- constructor 指回了Object -->
        Copy after login
      • 我们也可以通过Object.getOwnPropertyDescriptors()方法获取Object.prototype中的所有自身属性的描述符。
        console.log(Object.getOwnPropertyDescriptors(Object.prototype)) // 如下长截图所示
        Copy after login
        Detailed explanation of JavaScript prototype and prototype chain knowledge points

    4.原型链关系内存图

    Detailed explanation of JavaScript prototype and prototype chain knowledge points

    【相关推荐:javascript视频教程web前端

    The above is the detailed content of Detailed explanation of JavaScript prototype and prototype chain knowledge points. For more information, please follow other related articles on the PHP Chinese website!

    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

    Video Face Swap

    Video Face Swap

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

    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)

    How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

    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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

    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 JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

    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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

    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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

    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

    Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

    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

    How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

    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 and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

    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

    See all articles