Table of Contents
What is a prototype?
The relationship between constructors, instances, and prototypes
constructor
原型链
Home Web Front-end JS Tutorial Detailed explanation of js prototype usage

Detailed explanation of js prototype usage

May 24, 2018 am 11:00 AM
javascript use Detailed explanation

This time I will bring you a detailed explanation of the use of js prototypes. What are the precautions when using js prototypes? The following is a practical case, let’s take a look.

What is a prototype?

In javascript, the prototype is an object, and the inheritance of properties can be achieved through the prototype.

    let personBase = new Object()
    personBase.gender = '男'
    let animal = {
        eyeNumber: 2
    }
    let time = function () {
        let timeType = 'seconds'
    }
Copy after login

The three objects created above can be used as the prototype of any function.

function Person (age) {
  this.age = age
}
Person.prototype = personBase
let tom = new Person(18)
console.log(tom.age) // 18
console.log(tom.gender) // '男'
Copy after login

personBase is the prototype of Person. So ConstructorPerson inherits the gender attribute from personBase

Prototype: Every JavaScript object (assumed to be A , except null) will be associated with another object when it is created. This object is what we call the prototype. Every object will "inherit" properties from the prototype.

A, probably a function in most coding scenarios. Functions inherit from Function by default, that is, Function defaults to the prototype of all functions. When we add a prototype object to the function through the prototype attribute, the prototype object will be added to the near end of the prototype chain. Of course, A can also be other data types (Number, String, Array, Boolean), such as Number type. When we initialize the variable through literal method (var a = 1), it is equivalent to Instantiate a variable through the constructor method (var a = new Number(1)), that is, the variable created through the literal method is also an instance of Number. So we can realize the inheritance of properties and methods through the prototype attribute of Number. (Of course this is not recommended)

The relationship between constructors, instances, and prototypes

The key to understanding the relationship between these three is to understandprototype,# The connection between ##proto<a href="http://www.php.cn/code/8201.html" target="_blank"></a> and constructor:

Attribute-prototypeFunction attribute, pointing to the prototypeInstance attributes, pointing to the prototypeconstructorPrototype attributes, pointing to the constructor

在JavaScript中,每个函数都有一个prototype属性,当一个函数被用作构造函数来创建实例时,该函数的prototype属性值将被作为原型赋值给所有对象实例(设置实例的proto属性),也就是说,所有实例的原型引用的是构造函数的prototype属性。同时在原型对象中,包含一个"constructor"属性,这个属性对应创建所有指向该原型的实例的构造函数(有点拗口,就是constructor属性指向构造函数)。这三者的关系可以用下面的示例图表示:

Detailed explanation of js prototype usage

所以构造函数通过 prototype 属性指向自己的原型。 构造函数的实例在创建后通过 proto 属性指向构造函数的 prototype 的对象,即实例函数也指向原型。构造函数和实例都通过属性指向了原形。

代码示例:

    function Person () {}
    let manPerson = new Person()
    manPerson.proto === Person.prototype // true
    Person.prototype.constructor === Person // true
    manPerson.constructor === Person.prototype.constructor // true
Copy after login
  • manPerson是构造函数Person的实例

  • manPersonproto属性与Personprototype属性保存的值相等,即他们指向同一个对象原形

  • Person 的原形(Person.prototype)通过constructor属性指向 构造函数 Person ,即 Person和他的原形实现了相互引用

  • 实例的constructor属性与原形的constructor属性相等。这里实例的constructor属性是继承自原形的constructor属性。

反过来原型和构造函数是没有指向实例的引用,因为一个构造函数会有N个实例。javascript通过实例的  proto 属性来访问共同的原形。

所有函数都是 Function 构造函数的实例,而且函数也是一个对象
同时函数实例的字面量方式创建 function too(){} 等同于构造函数方式创建 let foo = new Function()
    foo instanceof Function // true
    too instanceof Function // true
    foo.proto === too.proto // true
    foo.proto === Function.prototype // true foo是Function的实例
Copy after login

所以too、foo都是Function的实例,他们的_proto指向的是Function构造函数的原型。

通过上面的示例代码分析,这里主要涉及到 prototypeprotoconstructor 这3个属性的关系。

我们再次梳理一下:

  • 对于所有的对象,都有proto属性,这个属性对应该对象的原型

  • 对于函数对象,除了proto属性之外,还有prototype属性,当一个函数被用作构造函数来创建实例时,该函数的prototype属性值将被作为原型赋值给所有对象实例(也就是设置实例的proto属性)

  • 所有的原型对象都有constructor属性,该属性对应创建所有指向该原型的实例的构造函数

  • 函数对象和原型对象通过prototypeconstructor属性进行相互关联

所以上面的关系图其实可以于理解为:

Detailed explanation of js prototype usage


题外话:

    Function.prototype === Function.proto
Copy after login

先有鸡还是先有蛋?怎么 Function 作为构造函数 与 Function 作为实例对象的原型相等

在JavaScript中,Function构造函数本身也算是Function类型的实例吗?Function构造函数的prototype属性和proto属性都指向同一个原型,是否可以说Function对象是由Function构造函数创建的一个实例?
相关问题
JavaScript 里 Function 也算一种基本类型?
在JavaScript中,Function构造函数本身也算是Function类型的实例吗?

对于这类问题也可以不用深究。


constructor

原型的constructor属性指向对应的构造函数

    function Person() {
    }
    console.log(Person === Person.prototype.constructor); // true
Copy after login

原型链

当理解了原形的概念后,原形链就比较好理解了。

Because every object and prototype has a prototype, the prototype of the object points to the parent of the object, and the prototype of the parent points to the parent of the parent. These prototypes are connected layer by layer to form a prototype chain. .JavaScript objects point to chains of prototype objects through proto. The concept of the prototype chain is not difficult to understand. When accessing the properties of an object, it not only searches on the object, but also searches for the prototype of the object and the prototype of the prototype of the object. It searches upwards layer by layer until it finds a If the attribute whose name matches reaches the end of the prototype chain, the value of the attribute is returned if found. Otherwise, undefind is returned (the end of the prototype chain is null).

Regarding the relationship between the prototypes of various data types in JavaScript, you can refer to the following figure to understand:

Detailed explanation of js prototype usage

I believe you have mastered the method after reading the case in this article, and more How exciting, please pay attention to other related articles on php Chinese website!

Recommended reading:

Detailed explanation of the steps to use React-router v4

detailed explanation of the steps for nodejs express to configure a self-signed https server

proto

The above is the detailed content of Detailed explanation of js prototype usage. 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)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

See all articles