当前位置:网站首页>JS prototype and prototype chain Paramecium can understand
JS prototype and prototype chain Paramecium can understand
2022-06-23 01:32:00 【hhzzcc_】
Official account , You can get a red envelope for takeout every day

1、 Concept
Move from MDN - The prototype chain of the instance object points to the prototype of its construction method . Prototypes use prototype visit , The prototype chain uses __proto__ visit , although __proto__ Larger mainstream browsers support , but MDN The following methods are recommended for reading and writing prototype chains , For the convenience of explaining the article __proto__ For example .
// get __proto__Object.getPrototypeOf();// set __proto__Object.setPrototypeOf();
About prototype and prototype chain , A simple example
const object = new Object();The above code shows object Be being Object Constructed instance object ,Object Is constructed object Construction method of , So we can get the instance object according to the concept object Prototype chain pointing construction method Object The prototype of the
object.__proto__ === Object.prototype; // true// orObject.getPrototypeOf(object) === Object.prototype; // true
2、new
new What did you do , Again from MDN Move down the concept :
Create an empty simple JavaScript object ( namely {});
For step 1 Add properties to the newly created object __proto__, Link this property to the prototype object of the constructor ;
Will step 1 The newly created object serves as this The context of ;
If the function does not return an object , Then return to this.
Manually implement a :
const myNew = (constructor, ...params) => {const obj = Object.create(null);obj.__proto__ = constructor.prototype;const result = constructor.call(obj, ...params);return typeof result === 'object' ? result : obj;};
Test it
function Person(type) { this.type = type || 'person'; }const student = myNew(Person, 'student');console.log(student);

Test it again js Self contained new
function Person(type) { this.type = type || 'person'; }const student = new Person('student');console.log(student);
The result is the same

3、Object.create(null)
const obj1 = Object.create(null);const obj2 = new Object();const obj3 = {};
There are three common methods for creating objects ,Object.create(null) What is created is a pure and empty object that does not contain a prototype chain , The second and third will create prototype chains , The third one can be understood as the second one , More common , Print their results separately
The first one is :

The second kind :

The third kind of , The result is the same as the second :

The rule of the attribute in the object is that if the current object cannot find the attribute, it will follow the prototype chain , Go up one layer at a time , until null, The following code is an example
Object.prototype.a = 1;const obj = {};console.log(obj.a); // 1
So if your project requires a lot of performance , It is not recommended to use code like the following to get the property value , Because when object properties a When it doesn't exist, it will try to traverse higher-level prototype properties , until null, The performance will be worse if you write like this
const a = obj.a || 2;You can use Object.create(null) Create a pure object without a prototype chain , Or use Object.hasOwnProperty, He will only access the properties of the current object and will not traverse the prototype chain
const a = obj.hasOwnProperty('a') ? obj.a : 2;4、 Inherit
Let's talk about it first. ES6 Medium class keyword , as follows
class Person {construstor() { this.type = 'person'; }getType() { return this.type; }}
Form like java Medium class grammar , But he's just a grammar sugar , The principle is still an object , amount to
function Person() {this.type = 'perosn';}Person.prototype.getType= function() { return this.type; }
class Inheritance is also very simple , and java The use of extends and super
class Student extends Person {construstor() {super();this.type = 'student';}}const student = new Student();// studentconsole.log(student.type);// studentconsole.log(student.getType());
extends、super and class It is also a grammar sugar , Its core operation is - extends Enable the instance object to access the inherited object properties and prototype properties ,super Is to call the constructor to inherit , And will this point at him , Implement a simple version of single inheritance extends and super
// extends, You can also use Object.create Formal realizationfunction myExtends(a, b) {a.prototype.__proto__ = b.prototype;}// superfunction mySuper(a, b, ...params) {a.call(b, ...params);}function Student() {// Call the parent class constructormySuper(Person, this);this.type = 'student';}// Student Inherit PersonmyExtends(Student, Person);const student = new Student();// studentconsole.log(student.type);// studentconsole.log(student.getType());
The test print results are the same
By the way ,js The so-called override of a parent method in a subclass , Just because the newly overridden method is closer to the instance object in the prototype chain , So the call priority is higher
5、instanceof
perform a instanceof b after , Will judge a Whether the prototype chain of points to b The prototype of the , If not, it will always follow the prototype chain for comparison , Until null
student instanceof Student // truestudent instanceof Person // truestudent instanceof Object // true
We can manually implement a
function myInstanceof(a, b) {let result = a;while(result.__proto__) {result = result.__proto__;if (result === b.prototype) return true;}return null;}
Test printing , The result is the same
student instanceof Student // truestudent instanceof Person // truestudent instanceof Object // true
6、 Conclusion
Take time to consolidate and record the basic knowledge at the weekend , If there is any error in the above contents, please point it out in time

You can pay attention to my official account. , Are original technical articles , Let's make progress together. !
边栏推荐
- SQL programming task02 job - basic query and sorting
- How to calculate the position of gold ETF
- Software construction course ADT and OOP understanding
- Wallys/DR7915-wifi6-MT7915-MT7975-2T2R-support-OpenWRT-802.11AX-supporting-MiniPCIe
- [luogu] p1083 [noip2012 improvement group] classroom borrowing (difference)
- Flink synchronizes MySQL data to es
- Vector 2 (friend and copy construction)
- Vector 3 (static member)
- 时间复杂度
- Day260: the number III that appears only once
猜你喜欢

SFOD:无源域适配升级优化,让检测模型更容易适应新数据

Installation record of ros1noetic in Win 11

Day367: valid complete square

3DMAX modeling notes (I): introducing 3DMAX and creating the first model Hello World

3D printing microstructure

Psychological analysis of the safest spot Silver

Development status of full color LED display
![[hdu] P6964 I love counting](/img/ff/f8e79d28758c9bd3019816c8f46723.png)
[hdu] P6964 I love counting

基于深度学习的视觉目标检测技术综述
![[launch] redis Series 2: data persistence to improve availability](/img/f4/5bc7ca3e17c6656e71df515182842e.png)
[launch] redis Series 2: data persistence to improve availability
随机推荐
SAP ui5 application development tutorial 103 - how to consume the trial version of the third-party library in SAP ui5 applications
SQL programming task02 job - basic query and sorting
B tree and b+ tree
[initial launch] there are too many requests at once, and the database is in danger
Charles garbled code problem solving
Wallys/DR7915-wifi6-MT7915-MT7975-2T2R-support-OpenWRT-802.11AX-supporting-MiniPCIe
Real topic of the 2020 Landbridge cup provincial competition - go square (dp/dfs)
New progress in the construction of meituan's Flink based real-time data warehouse platform
Thead safety experience
Node fetch download file
Add expiration time for localstorage
Fluentd is easy to use. Combined with the rainbow plug-in market, log collection is faster
[template] KMP
[learning notes] roll back Mo team
Ansible learning summary (8) -- Summary of ansible control right raising related knowledge
Project directory navigation
SQL programming task05 job -sql advanced processing
Component development
Network module packaging
Steps to implement a container global component