当前位置:网站首页>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. !
边栏推荐
- On AI and its future trend | community essay solicitation
- Component development
- MySQL-Seconds_ behind_ Master accuracy error
- [hdu] P7079 Pty loves lines
- 07 project cost management
- Phantomjs Usage Summary
- Thead safety experience
- OSPF comprehensive experiment
- Yyds dry inventory solution sword finger offer: print the binary tree into multiple lines
- Vector 6 (inheritance)
猜你喜欢

Cadence spb17.4 - Allegro - optimize and specify the polyline connection angle of a single electrical line - polyline to arc
![[hdu] P6964 I love counting](/img/ff/f8e79d28758c9bd3019816c8f46723.png)
[hdu] P6964 I love counting

Autumn move script B

OSPF experiment in mGRE environment

Do you know the memory components of MySQL InnoDB?

07 project cost management

SQL programming task04 job - set operation

Module 8 job

Day367: valid complete square

Cadence spb17.4 - Chinese UI settings
随机推荐
Vector 1 (classes and objects)
Random decoding NLP
Vector 6 (inheritance)
Autumn move script a
Shell view help
[luogu] p1083 [noip2012 improvement group] borrow classroom (line segment tree)
Debian10 configuring rsyslog+loganalyzer log server
Sélecteur de hiérarchie
Overview of visual object detection technology based on deep learning
Analysis of current mainstream video coding technology | community essay solicitation
Day260: the number III that appears only once
B tree and b+ tree
Similar to attention NLP
Day500: keyboard line
層次選擇器
Char[], char *, conversion between strings
Get the start and end dates of the current week
SAP ui5 application development tutorial 103 - how to consume the trial version of the third-party library in SAP ui5 applications
The devil cold rice # 099 the devil said to travel to the West; The nature of the boss; Answer the midlife crisis again; Specialty selection
three. JS simulated driving tour art exhibition hall - creating super camera controller