当前位置:网站首页>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 :

  1. Create an empty simple JavaScript object ( namely {});

  2. For step 1 Add properties to the newly created object __proto__, Link this property to the prototype object of the constructor ;

  3. Will step 1 The newly created object serves as this The context of ;

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

Print

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());

extendssuper 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 realization function myExtends(a, b) {
     a.prototype.__proto__ = b.prototype;}// superfunction mySuper(a, b, ...params) {
     a.call(b, ...params);}function Student() {
     //  Call the parent class constructor   mySuper(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. !

原网站

版权声明
本文为[hhzzcc_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220516248618.html