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

H function

After the introduction of the previous chapter [Snabbdom source code parsing – opening], we will officially enter the code learning!

Our goal is to figure out how the h function creates a VNode.

h.ts

Path: SRC/package/h.t s

An overview of the code

import { vnode, VNode, VNodeData } from './vnode'
import * as is from './is'
Copy the code

I’ll leave that for later, but then we define some types, which are TypeScript methods, and then we define the helper function addNS which we’ll see when it gets called in a second, and then we define and export the h function, right

H function

Through a brief look at the code structure, we can clearly see that here we define 5 h functions through function overloading mechanism, but we need to pay attention to one thing, although this is written using TS, but will eventually be compiled into JS, but JS does not support function overloading. So what will it compile into?

Here’s a simple example:

So let’s simulate overloading in h and make some simple judgments

function addToZ(x: number) :number
function addToZ(x: number, y: number) :number
function addToZ(x: number, y? : number, z? : number) :number {
    if (y) {
        return x+y
    }
    if (z) {
        return x+z
    }
    return x
}
Copy the code

Eventually compile

function addToZ(x, y, z) {
    if (y) {
        return x + y;
    }
    if (z) {
        return x + z;
    }
    return x;
}

Copy the code

Going back to our h function, let’s look at the last h function

H The parameter and return value of the function

function h (sel: any, b? : any, c? : any) :VNode
Copy the code

Here we can learn:

  • The sel argument is a mandatory argument and has no type limit.

  • B (second parameter), C (third parameter); These two parameters are not required

  • The return type of the function is VNode

Now that we understand function overloading, it’s a lot easier to understand, because the essence of h is to process parameters and call vNode and return the value