Table of Contents
1: Constructor
Notes on constructors:
二: 原型对象 prototype
2.1 为什么有原型对象" >2.1 为什么有原型对象
2.2 原型对象的使用" >2.2 原型对象的使用
上述案例解决方案: " >上述案例解决方案: 
 三:对象原型 __proto__
3.1 什么是对象原型?" >3.1 什么是对象原型?
或者可以理解为:
3.2 关于对象原型__proto__的注意点 " >3.2 关于对象原型__proto__的注意点 
方法的查找原则:
四:构造函数 constructor 
4.1 为什么 constructor 也叫构造函数" >4.1 为什么 constructor 也叫构造函数
打印二者的constructor属性:
4.2 手动返回 constructor 的情况" >4.2 手动返回 constructor 的情况
其格式为:
Home Web Front-end JS Tutorial A brief introduction to JavaScript 'prototype' and 'prototype chain'

A brief introduction to JavaScript 'prototype' and 'prototype chain'

Jul 20, 2022 pm 02:11 PM
javascript

This article brings you relevant knowledge about javascript, which mainly introduces issues related to "prototype" and "prototype chain", including constructors, prototype objects prototype, objects Let’s take a look at the prototype and other contents, I hope it will be helpful to everyone.

A brief introduction to JavaScript 'prototype' and 'prototype chain'

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

What is a prototype? Prototype is a concept that we have not mentioned in the basic learning of JS. Prototype is a general term, which mainly includes prototype object (prototype) , Object prototype (__proto__), Prototype chain etc. According to statistics, these concepts are also frequently asked in interviews. This article will help you understand and master the relevant knowledge of prototypes, so that you will no longer be confused. .

1: Constructor

We have studied many object-oriented languages, such as java c, etc., but JavaScript is an exception. Before ES6, there was no concept of classes. How do we create objects? It turns out that before ES6, we used constructor to create instantiated objects. The constructor is a special function that contains the public characteristics of the object and must be coordinated with new It only makes sense to use them together.

Notes on constructors:

  • The first letter of the constructor name must be capitalized
  • The constructor should be used together with new
## 1.1 How to use the constructor

   <script> 
           function Animal(name,age){      //构造函数名首字母大写
                this.name=name;
                this.age=age;
                this.eat=function(){
                  console.log('我在吃东西');
                }
           }
           var dog=new Animal('旺财',3)     //要配合 new 一起使用创建对象
           console.log(dog.name);
           console.log(dog.age);
           dog.eat()
   </script>
Copy after login

##1.2 The execution process of constructor new

new has the following execution process:

    When new, an empty object will be created
  • This in the constructor points to this empty object
  • Execute the code in the constructor to assign a value to the empty object and add attribute methods
  • Return this object
1.3 Instance members and static members

Instance members:

    Instance members are members added using this inside the spectator attribute
  • Instance members can only be accessed through the instantiated object call and cannot be accessed through the constructor name
  •    <script>
               function Animal(name,age){
                    this.name=name;
                    this.age=age;
               }
               var dog=new Animal('旺财',3)
               console.log(dog.name);
               console.log(Animal.name);
       </script>
    Copy after login


Static members:

    Static members are created through the constructor itself Members
  • Static members can only be accessed through the constructor name, not through the instantiated object
  •    <script>
               function Animal(name,age){
                    this.name=name;
                    this.age=age;
               }
               var dog=new Animal('旺财',3)
               Animal.color='黑色'
               console.log(Animal.color);
               console.log(dog.color);
       </script>
    Copy after login


二: 原型对象 prototype

2.1 为什么有原型对象

在开始将原型对象是什么前,我们先说明一个案例,还是刚才的那个 Animal 类,我们创建了多个实例化对象,输出其实例化对象的两个方法的比较,我们发现输出了 false,即二者的这个复杂数据类型的地址不同,什么原因呢?

   <script> 
      function Animal(name,age){      
           this.name=name;
           this.age=age;
           this.eat=function(){
             console.log('我在吃东西');
           }
      }
      var dog=new Animal('旺财',3)     
      var cat=new Animal('咪咪',3)     
      var pig=new Animal('哼哼',3)     
      var fish=new Animal('咕噜',3)     
      var sheep=new Animal('咩咩',3)     
      console.log(dog.eat==cat.eat);
</script>
Copy after login

在我们创建实例化对象的过程中,new 的过程首先会创建一个新对象,但是复杂数据类型会领开辟一块空间存放(对象,方法),这就造成了构造函数内同样的方法被开辟了无数块内存,造成了内存的极度浪费

2.2 原型对象的使用

     构造函数原型 prototype 是构造函数内的一个属性,其属性是一个指针,指向一个对象,这个对象内存放的就是公共的方法,存在这个对象里的方法,再通过构造函数创建实例化对象时就可以公共利用这一个方法了,不需要再对多个相同的复杂数据类型开辟多个重复的内存空间。就是为了解决上述存在的内存浪费的问题,其也可以直接称为原型对象。

上述案例解决方案: 

解决方案我们使用原型对象存放公共方法,并且让实例化对象调用该方法,并且比较二者的地址是否相同

   <script> 
      function Animal(name,age){      
           this.name=name;
           this.age=age;
      }
      Animal.prototype.eat=function(){
          console.log('我在吃东西');
      }
      var dog=new Animal('旺财',3)     
      var cat=new Animal('咪咪',3)     
      dog.eat()
      cat.eat()
      console.log(dog.eat==cat.eat);
</script>
Copy after login

我们发现不但成功调用了这个方法,而且二者调用方法的地址是相同的,这就证明了,其公共的复杂数据类型只开辟了一块内存空间,减少了之前公共方法写在构造函数内部资源浪费的问题。


 三:对象原型 __proto__

3.1 什么是对象原型?

对象原型__proto__的作用是让你搞清楚一个问题:为什么给构造函数的prototype属性添加的方法,实例化对象却可以使用?这是因为每一个对象都有一个 __proto__属性(注意前后都是两个下划线),这个属性也是一个指针,指向的是其对应构造函数的原型对象 prototype,这就解释了为什么实例化的对象可以去调用原型对象里的方法。

或者可以理解为:

  • 原型对象prototype 等价于 对象原型 __proto__

3.2 关于对象原型__proto__的注意点 

我们要注意对象原型__protp__的作用仅仅是为了给查找原型对象内的内容提供一个方向,我们不需要使用它,只需要记住它指向对应的构造函数的原型对象 prototype 即可

方法的查找原则:

  • 首先去找实例化自身的构造函数身上有没有目标方法,有则调用
  • 如果自身构造函数身上没有,由于因为对象自身有属性__protp__,其指向构造函数的原型对象prototype,则会去找原型对象身上有没有该方法

四:构造函数 constructor 

4.1 为什么 constructor 也叫构造函数

对象原型 __proto__ 身上和构造函数的原型对象 prototype 身上都有一个 constructor 属性,之所以叫 constructor 叫构造函数,是因为这个属性指向的是对应的构造函数本身,其主要用于记录实例化的对象引用于哪一个构造函数

打印二者的constructor属性:

   <script> 
      function Animal(name,age){      
           this.name=name;
           this.age=age;
      }
      Animal.prototype.eat=function(){
         console.log('我在吃东西');
      }
     var dog=new Animal('旺财',4)
     console.log(dog.__proto__.constructor);
     console.log(Animal.prototype.constructor);
</script>
Copy after login

 我们发现打印出来结果确实为构造函数本身

4.2 手动返回 constructor 的情况

更多时候我们需要手动返回 constructor 指向的哪个构造函数,例如构造函数的原型对象中以对象的形式存入多个公共方法时,就会出现以下情况:

   <script> 
      function Animal(name,age){      
           this.name=name;
           this.age=age;
      }
      Animal.prototype={
        eat:function(){
          console.log('我在吃东西');
        },
        run:function(){
          console.log('我在跑');
        }
      }
      var dog=new Animal('wangchai',3)
      console.log(Animal.prototype.constructor);
      console.log(dog.__proto__.constructor);
</script>
Copy after login


 我们发现其找不到对应的构造函数了,这是因为我们给其原型对象添加方法的添加方式导致的,这钱我们采取的以.方式添加,是在原有基础上追加添加的,不会覆盖掉内部原有的内容。而我们采用=的方法以对象形式添加,其实是一个赋值的过程,将原有内容也给覆盖掉了,这就导致 prototype 内部原有的 constructor 方法被覆盖掉了

 这时就需要我们手动返回 constructor 来找到返回的是哪个的构造函数

   <script> 
      function Animal(name,age){      
           this.name=name;
           this.age=age;
      }
      Animal.prototype={
        constructor:Animal,
        eat:function(){
          console.log('我在吃东西');
        },
        run:function(){
          console.log('我在跑');
        }
      }
      var dog=new Animal('wangchai',3)
      console.log(Animal.prototype.constructor);
      console.log(dog.__proto__.constructor);
</script>
Copy after login

这样我们就可以成功拿到其 constructor 指向的哪个构造函数了

其格式为:

  • constructor : 构造函数名 

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

The above is the detailed content of A brief introduction to JavaScript 'prototype' and 'prototype chain'. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 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.

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

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).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

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

See all articles