1. class VNode {
    2. constructor(tagName, attrs, children) {
    3. this.tagName = tagName
    4. this.attributes = attrs
    5. this.children = children
    6. }
    7. render() {
    8. let element = document.createElement(this.tagName)
    9. Object.keys(this.attributes).forEach(key => {
    10. element.setAttribute(key, this.attributes[key])
    11. })
    12. this.children.forEach(child => {
    13. element.appendChild(child.render())
    14. })
    15. return element
    16. }
    17. }
    18. class TextNode {
    19. constructor(content) {
    20. this.content = content
    21. }
    22. render() {
    23. return document.createTextNode(this.content)
    24. }
    25. }

    usage

    1. let virtualDom = new VNode('div', {class: 'container'}, [
    2. new TextNode('some content'),
    3. new VNode('span', {}, [
    4. new TextNode('other content')
    5. ])
    6. ])

    虚拟DOM实现 - 图1