Object.defineProperty(obj,"b",{
value:10,
writeable:false,
enumber:false,
configurable:false
})
obj.b.value = 11;
for(let item in obj) {
console.log(item);
}
console.log(obj.b)
对象的get和set方法
进行读操作时候触发get方法,进行写操作时触发set方法
Object.defineProperty(obj,"b",{
value:10,
writeable:false,
enumber:false,
configurable:false,
get() {
return 21021
}
})
监听defineProperty的getter setter方法
视图(实现了给页面解耦,维护性复用性更高)
虚拟DOM
为什么引入虚拟DOM?
提供一种方便的工具让效率得到保证,保证最小化的DOM操作。改变某个节点不需要重排整个项目模板。虚拟DOM实则是js模拟了DOM(通过编译HTML页面,调用js,因为document对象结果返回文档js对象)
console.dir(document)//console.dir()可以显示一个对象的所有属性和方法
document.body.childNode下面的标签就是文档树结构,vue就是通过这个方法获取虚拟DOM
再通过调用渲染的方法可以通过虚拟DOM渲染出真的页面
function vElement(tagment,prop,children) {
if(!(this instanceof vElement)) {
return new vElement(tagment,prop,children);
}
if(Object.prototype.toString.call(prop) === "[object Array]") {
children = prop;
prop = {}
}
this.tagName = tagName;
this.prop = prop;
this.children = children;
var count = 0;
this.children.forEach(function(child,index){
if(child instance of vElement) {
count += child.count;
}
count++;
})
this.count = count;
}
对于上文的if(! this instance of vElement)是什么作用,其实我们只需要理解instanceof是什么作用,官网给的解释是a instanceof b 判断a是否是b的构造函数或者实例对象
我们通过new关键字实例化以后的对象this指向function本身可以认为是function的一个实例对象所以通过这种方式可以判断出咱们是否发生了实例化的操作。
编写render函数把上面返回的虚拟dom渲染成真正的dom
Velement.prototype.render = function() {
var el = document.createElement(this.tagName);
var children = this.children;
var prop = this.prop;
for(var item in prop) {
var curProp = prop[item];
el.setAttribute(item, curProp)
}
children.forEach(function(child,index){
if(child instanceof vElement) {
var childDom = child.render();
} else {
var childDom = document.createNodeText(child)
}
el.appendChild(childDom)
})
return el;
}