JavaScript advanced prototype and prototype chain

Front end Xiaoxin 2021-02-23 03:43:34
javascript advanced prototype prototype chain


Prototype and prototype chain have always been the focus of research JavaScript Key and difficult points , Mastering this part will make our work more efficient , And that's what interviewers have to ask .

First , We need to be clear that , stay ES6 Before , We don't create an instance through a class (class), It's done directly with constructors .

One 、 Constructors

adopt new Function name A function that instantiates an object is called a constructor . Any function can exist as a constructor . The first letter of a constructor is usually capitalized .

that , We use constructors to create an object .

function Person(name , age , sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
var person = new Person("Tony" , 18 , " male ");
console.log(person.name); // Tony
 Copy code 

The above code is to create a Person Constructor for , stay Person In the constructor , Three properties are added to each object (name,age,sex), That is to say, every time the constructor executes, it creates a new Person object .

Let's review it briefly , Let's get down to business .

Two 、 Prototype

prototype

stay JS in , Every time you define a function , Will default to bring one prototype attribute , This property points to the one created by the constructor example The prototype of the , And this property is the value of an object data type .

Prototype : every last JS object (null With the exception of ) Another object will be associated with it when it is created , This object is what we call prototype , Every object will be from prototype " Inherit " attribute .

Take a prototype Demo:

function Person() { }
Person.prototype.name = 'Tony'; // Be careful :prototype It's a function that has properties 
var person1 = new Person();
var person2 = new Person();
console.log(person1.name); // Tony
console.log(person2.name); // Tony
 Copy code 

The relationship between the constructor and the instance prototype :  The relationship between the constructor and the instance prototype : ad locum Person.prototype Represents an instance prototype . Prototype object is equivalent to a public area , All instances of the same class can access the prototype object , We can share the content of objects , Set uniformly to the prototype object .

3、 ... and 、 Prototype chain

above , We illustrate examples and instance prototypes , So how can we express the relationship between the two ? At this time, we will talk about the following two attributes

__proto__

This is every one JS object ( except null ) All have a property , It's called __proto__, This property points to the prototype of the object .

person.__proto__ === Person.prototype // true
 Copy code 

__proto__ Most browsers support this non-standard method access prototype , But it doesn't exist in Person.prototype in , actually , It comes from Object.prototype , It's not so much an attribute , It's more like a getter/setter, When using obj.__proto__ when , It can be understood as returning Object.getPrototypeOf(obj).

constructor

Each prototype has a constructor Property points to the associated constructor .

Person === Person.prototype.constructor // true
 Copy code 

When getting person.constructor when , Actually person Not in China constructor attribute , When can't read constructor Attribute , From person The prototype of Person.prototype Read from , It happens that the prototype has this property , therefore :

person.constructor === Person.prototype.constructor
 Copy code 

Diagram of instance prototype and constructor :  Diagram of instance prototype and constructor Prototype chain : stay JS in , Everything is object , There is also a relationship between objects , It doesn't exist in isolation . The inheritance relationship between objects , stay JS China is through prototype Object points to the parent object , Until pointing Object Object up to , So it forms a chain that the archetype points to , The technical term is prototype chain .

Examples and prototypes

When we read a property or method of an instance , It will first look for... In the object itself , If so, use , If not, it will go to the prototype object to find , If found, use . If not, go to the prototype to find , All the way to the top Object until ,Object The prototype of the object has no prototype (Object yes JS The base class for all object data types in ( Top class ) stay Object.prototype Not on __proto__ This attribute ), If in Object The prototype is still missing , Then return to undefined.

function Person() {}
Person.prototype.name = 'Tony';
var person = new Person();
// When we give instance objects person Added name attribute , Print person.name when , The result is name Value Ken.
person.name = 'Ken';
console.log(person.name) // Ken
// When we delete person Of name Attribute , Read again person.name, from person Can't find name The attribute will be from person The prototype of person.__proto__ and Person.prototype Search for name attribute , Because before we added , So I found name The attribute is Tony.
delete person.name;
console.log(person.name) // Tony
 Copy code 

We can use the hasOwnProperty() To check whether the object itself contains the property , If its own properties exist , Then return to true, Otherwise false; Use in When checking whether an object contains an attribute , If not in the object but in the prototype , Will return true, If none, return false.

function Person() {
this.name = 'Tony'
}
Person.prototype.age = 18;
var person = new Person();
console.log(person.hasOwnProperty('name')); // true
console.log(person.hasOwnProperty('age')); // false
console.log('name' in person); // true
console.log('age' in person); // true
console.log('a' in person); // false
 Copy code 

Last , The chain of interrelated prototypes is the chain of prototypes , That's the blue line :  Insert picture description here


Read the summary carefully , Should be right JS Let's have a deep understanding of the prototype and prototype chain of , In fact, this part still needs careful consideration , After all, it's the underlying principle .

版权声明
本文为[Front end Xiaoxin]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210222134322238m.html

  1. Configure the certificate to enable ngnix to publish the trusted website of HTTPS
  2. Javascript数据类型
  3. HTTP interface debugging tool! 48000 star HTTP command line client!
  4. Parameter encryption of front end URL link band
  5. HTTP interface debugging tool! 48000 star HTTP command line client!
  6. Three front end frameworks: data binding and data flow
  7. Reading Axios source code (1) -- exploring the realization of basic ability
  8. Event bubble and capture in JavaScript
  9. 【微前端】微前端最終章-qiankun指南以及微前端整體探索
  10. R & D solution e-Car front end monitoring system
  11. [JS] 877 - 35 wonderful knowledge of JavaScript, long experience!
  12. R & D solution e-Car front end monitoring system
  13. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%
  14. 解决ajax跨域问题【5种解决方案】
  15. Top ten classic sorting of JavaScript
  16. HTTP 1. X learning notes: an authoritative guide to Web Performance
  17. Vue3 component (IX) Vue + element plus + JSON = dynamic rendering form control component
  18. My http / 1.1 is so slow!
  19. Why Vue uses asynchronous rendering
  20. The response status was 0. Check out the W3C XMLHttpRequest Level 2 spec for
  21. The tapable instance object hook of webpack4. X core tool library
  22. The tapable instance object hook of webpack4. X core tool library
  23. Using libcurl for HTTP communication in C + +
  24. Using libcurl for HTTP communication in C + +
  25. Using CSS variable in Vue
  26. Deeply understand the update of state and props in react
  27. No matter how fast the Internet is, it's useless! In addition to Baidu disk, there is this website slow to let you eat shriveled
  28. Baidu share does not support the solution of HTTPS
  29. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  30. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  31. Vue cli creates vue3 project
  32. Nginx reverse proxy for windows authentication using NTLM
  33. Rust tutorial: introduction to rust for JavaScript developers
  34. Deploying personal blog to Tencent cloud with serverless framework
  35. R & D solution e-Car front end monitoring system
  36. JavaScript advanced learning
  37. Spend 1 minute to master these 5 ppt tips, courseware making less detours
  38. Vue: vuex persistent state
  39. React native gets the current network state of the device Netinfo
  40. High performance nginx HTTPS tuning - how to speed up HTTPS by 30%
  41. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  42. JavaScript advanced: Javascript object-oriented, JavaScript built-in object, JavaScript BOM, JavaScript encapsulation
  43. Vue determines whether the El form in the elementui is updated or changed. If it changes, it will prompt whether to save it. If it does not change, it will leave directly
  44. Algorithm problem: sum of two numbers -- JavaScript and Java implementation
  45. High performance nginx HTTPS tuning
  46. JQuery advanced
  47. day 30 jQuery
  48. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  49. TCP/IP 开胃菜 之 HTTP
  50. JQuery:JQuery Basic syntax, jQuery selector, jQuery DOM, comprehensive case check box, comprehensive case random picture
  51. JavaScript data type
  52. [micro front end] the final chapter of micro front end - Qiankun guide and overall exploration of micro front end
  53. Solve Ajax cross domain problem [5 solutions]
  54. HTTP of TCP / IP appetizer
  55. Optimization of pod creation efficiency in serverless scenario
  56. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  57. First knowledge of HTTP / 1.1
  58. First knowledge of HTTP / 1.1
  59. Webpack learning notes series 05 devserver
  60. Webpack learning notes series 04 - resource processing optimization