class Element {
constructor(tagName, props, children) {
this.tagName = tagName;
this.props = props;
this.children = children;
}
render() {
const dom = document.createElement(this.tagName);
// 设置标签属性值
Reflect.ownKeys(this.props).forEach(name =>
dom.setAttribute(name, this.props[name])
);
// 递归更新子节点
this.children.forEach(child => {
const childDom =
child instanceof Element
? child.render()
: document.createTextNode(child);
dom.appendChild(childDom);
});
return dom;
}
}
// 代码出处链接:https://juejin.cn/post/6844903998768545800
// 以上代码仅用于展示 Reflect.ownKeys 的用法
Object.keys能返回方法属性,只不过Object.keys返回的是可枚举属性,当设置对象的enumerable设置为false, 那就无法遍历。 Reflect.ownKeys 返回所有的自己属性,不管可枚举还是不可枚举,所以可以遍历出方法属性。