This is the second day of my participation in Gwen Challenge

The application of linked list in the front end

The use of linked lists in the front end is often used with prototypes and prototype chains. In the following article, we will explain the application of linked lists in the front end.

Linked lists VS arrays

  • Arrays: Adding and removing non-beginning and end elements often requires moving elements.
  • Linked list: adding and deleting non-beginning and end elements,There is no need to move elements, just need to changenextCan point to.

2, JS linked list

  • There are no linked lists in Javascript;
  • You can use Object to simulate linked lists.

Front-end and linked list: prototype chain in JS

What is the prototype?

  • inJavascriptIn, each object initializes a property within it, which isA prototype object(Prototype for short).

What is the prototype chain?

  • When we access a property of an object, if the property doesn’t exist inside the object, it goesprototypeLook for this property, this propertyprototypeYou’ll have your ownprototype, so have been looking for down, so step by step to find the shape of a chain, and through[[prototype]]Property join, the process of this join is calledPrototype chain.
  • The essence of the prototype chain isThe listAnd the nodes on the prototype chain areVarious prototype objects, such as:Function.prototypeObject.prototype… .
  • Prototype chain pass__proto__Property connects various prototype objects.

3. What is the prototype chain like?

(1) arr → array. prototype → Object. Prototype → null

  • Arr.__ proto __ = array. prototype;
  • Array.__ proto __= Object. Prototype;
  • Object.__ proto __= null.

To demonstrate this relationship, use code:

let arr = [];
console.log(arr.__proto__ === Array.prototype);    // true
console.log(arr.__proto__.__proto__ === Object.prototype);    // true
console.log(arr.__proto__.__proto__.__proto__);  //null
Copy the code

Explanation:

__proto__ represents the prototype of arr. In this example, let arr = [] indirectly calls new Array, Array.prototype = array. prototype = arr.__proto__ = array. prototype The stereotype property of arR is the stereotype object of the constructor Array.

Similarly, we find that arr.__proto__ is equal to array. prototype, so going back to the source, Array has its own prototype attribute, What would the Array’s prototype property arr.__proto__.__proto__ equal?

In fact, in JS, Object is the parent Object of all objects, that is, most objects have a common prototype object.prototype. __proto__ = object. prototype; prototype = arr.__proto__; prototype = Object. __proto__.__proto__.__proto__ is null, which means that the prototype chain has reached the most source position.

Conclusion:

  • ObjectIs for all objectsParent object.
  • As you can see from the example above, all prototype objects doPointing to the firstTheir own__proto__Properties,And then point toHis own prototype,The last pointParent objectObjectThe prototype.

Here are two more examples that you can test according to the method of (1).

(2) obj → Object. Prototype → null

  • Object. __ proto __ = Object. Prototype;
  • Object.__ proto __= null.

Use code to demonstrate this relationship:

let obj = {};
console.log(obj.__proto__ === Object.prototype);    // true
console.log(obj.__proto__.__proto__);  //null
Copy the code

(3) func → Function. Prototype → Object. Prototype → null

  • Prototype = Function.
  • Function.__ proto __= Object. Prototype;
  • Object.__ proto __= null.

Use code to demonstrate this relationship:

let func = function(){};console.log(func.__proto__ === Function.prototype);    // true
console.log(func.__proto__.__proto__ === Object.prototype);    // true
console.log(func.__proto__.__proto__.__proto__);  //null
Copy the code

(4) Prototype in class

1) Let’s look at the first piece of code.

/ / parent class
class People{
    constructor(){
        this.name = name;
    }
    eat(){
        console.log(`The ${this.name} eat something`); }}/ / subclass
class Student extends People{
    constructor(name, number){
        super(name);
        this.number = number;
    }
    sayHi(){
        console.log(` name:The ${this.name}Student number:The ${this.number}`); }}console.log(typeof Student); //function
console.log(typeof People); //function

let xialuo = new Student('charlotte'.10010);
console.log(xialuo.__proto__);
console.log(Student.prototype);
console.log(xialuo.__proto__ === Student.prototype); //true
Copy the code

As you can see from the above code, the value of typeof Student and typeof People is function, so class is actually a function, i.e. syntactically sugar.

Looking at the three console.log printed values below, let’s tease out the relationship between a prototype. Student is a class, so each class has its explicit prototype, while Xialuo is an instance, and each instance has its implicit prototype __proto__. The relationship between the two is that the __proto__ of instance Xialuo points to the corresponding class prototype.

Therefore, the following conclusions can be drawn about prototypes in class:

  • eachclassThey all have explicit archetypesprototype
  • Each instance has an implicit stereotype__proto__ ;
  • The instance__proto__Point to the correspondingclassprototype

2) Let’s look at the second code.

/ / parent class
class People{
    constructor(){
        this.name = name;
    }
    eat(){
        console.log(`The ${this.name} eat something`); }}/ / subclass
class Student extends People{
    constructor(name, number){
        super(name);
        this.number = number;
    }
    sayHi(){
        console.log(` name:The ${this.name}Student number:The ${this.number}`); }}let xialuo = new Student('charlotte'.10010);
console.log(xialuo.name); / / charlotte
console.log(xialuo.number); / / 10010
console.log(Student.sayHi()); // Name: Charlotte, student ID: 10010

Copy the code

As you can see from the above code, the Student class has the number attribute, so it reads the value of its number directly. At the same time, it does not have the name attribute, but since it inherits from People, when it cannot find the name attribute, it automatically looks in __proto__, so it looks in its parent class People.

So, the prototype-based execution rules can be drawn from the above demo:

  • Get the attributes first (e.gxialuo.namexiaoluo.number) or get the execution method (e.gxialuo.sayhi());
  • After obtaining, search for its own attributes and methods first;
  • If you can’t find it, go automatically__proto__In the search.

(5) New Object() differs from object.create ()

  • {}Is equivalent tonew Object(), and based on theObject.prototype
  • Object.create(null)No prototype;
  • Object.create({... })Prototypes can be specified.

4. Prototype chain knowledge points

(1) If A can find B.prototype along the prototype chain, then an instanceof B is true.

Example 1:

let obj = {};
console.log(obj instanceof Object); //true
Copy the code

For obj instanceof Object, the left and right operation, obj instanceof Object means to check whether there is a prototype Object on the prototype chain of obj, that is, whether obj is an instanceof Object.

Example 2:

let func = function(){};console.log(func instanceof Function); //true
console.log(func instanceof Object); //true
Copy the code

In the case of func, func is an instance of both Function and Object.

(2) If the x attribute is not found on the object A, the x attribute will be searched along the prototype chain.

For example:

const obj = {};

Object.prototype.x = 'x';

console.log(obj.x); //x
Copy the code

As you can see from the above code, obj does not find the value of x in its own region, so it will continue to look for its prototype chain and finally find Object.prototype.x, so obj.x = x.

Let’s review these two points with two common interview questions.

5, often meet test questions

(1) Instanceof principle

A instanceof B is true if A can find b. prototype along the prototype chain.

Solution: Iterate through the prototype chain of A, returning true if b. prototype is found, false otherwise.

Code demo:

// Check whether A is an instance of B
const instanceOf = (A, B) = > {
    // define A pointer P to A
    let p = A;
    // Continue execution if P exists
    while(p){
        // check whether the P value is equal to B's prototype object
        if(p === B.prototype){
            return true;
        }
        // Iterate through the prototype chain of A until you find the prototype of B
        p = p.__proto__;
    }
    return false;
}
Copy the code

(2) Look at the code and get the output result.

Take a look at the following code and give four console.log printed values.

let foo = {};
let F = function(){};
Object.prototype.a = 'value a';
Function.prototype.b = 'value b';

console.log(foo.a); //value a
console.log(foo.b); //undefind

console.log(F.a); //value a
console.log(F.b); //value b
Copy the code

If the x attribute is not found on the A object, then the x attribute will be found along the prototype chain.

Solution: Specify the stereotype chain for variables foo and F, and find attributes A and B along the stereotype chain.

Foo is an Object, and its __proto__ attribute points to Object.prototype, so foo.a looks up its prototype chain for the value of object.prototype. a. Similarly, foo.b looks for a value in its prototype chain, but can’t find object.prototype. b, so it returns undefined. The same is true for F.a and F.b, which can be verified one by one.

Write at the end

Prototypes and prototype chains are basic knowledge in the front end! Almost every object we write about has a prototype and a prototype chain. Therefore, for the front end, if the relationship between the prototype and the prototype chain is not understood, it is easy to write all kinds of bugs unconsciously, which is a huge disaster for the subsequent maintenance and the program. So understanding prototypes and prototype chains is an essential skill for the front end.

So much for the application of linked lists in the front end! If you do not understand or wrong place also welcome to comment on the comment area or private letter I exchange ~

  • Concern about the public number Monday laboratory, do not regularly share learning dry goods, learning on the way not lost ~
  • If this article is useful to you, be sure to like it and follow it