“This is the third day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Snabbdom source code parsing

Then we started to learn the source code of Snabbdom

Why studySnabbdomThe source of

  • A:becauseVueThe virtual DOM is modifiedSnabbdomWe can figure it out when we’re doneVueThe implementation principle of.

Objective in this chapter

Find out what VNode is and how H and Patch work

The core of Snabbdom

  • Init function sets the module and creates the patch function

  • Use the H function to create JavaScript objects (vNodes) that describe the real DOM

  • The patch function compares the old and new VNodes

  • Update the changed content to the real DOM tree

Snabbdom source

  • Source code address:
    • Github.com/snabbdom/sn…
    • V2.1.0: github.com/snabbdom/sn…

H function

Next, let’s analyze the implementation of h function

  • Creates a VNode object

  • H function in Vue

  • The h function, first seen in HyperScript, uses JavaScript to create hypertext

H function, I have to say function overloading

Why do we need to mention function overloading here? The main reason is that our h function uses this concept

Function overloading

  • A function with a different number or type of arguments

  • There is no concept of overloading in JavaScript

  • TypeScript has the concept of overloading, which is not implemented in TypeScript but is coded to adjust parameters

Let’s use an example to better introduce the concept of function overloading

  • 1. Overload with different number of parameters
    function add(a: number, b: number) {
        console.log(a + b)
    }
    function add(a: number, b: number, c:number) {
        console.log(a + b + c)
    }
    add(1.2)
    add(1.2.3)
    Copy the code

    Here we defineTwo functions of the same nameaddIn languages that support function overloading, for exampleTypeScript, it can define two functions with the same name and distinguish the two functions by the different number of arguments

  • 2. Overloading of different parameter types
    function add(a: number, b: number) {
        console.log(a + b)
    }
    function add(a: number, b: string) {
        console.log(a + b + c)
    }
    add(1.2)
    add(1.'2')
    Copy the code

    Here we defineTwo functions of the same nameaddThe difference is that the type of the second parameter is different. Here we call a function with different parameters, so we call a different method