MVVM实现原理(一)——Object.defineProperty

168 阅读1分钟

红色框圈住的两个属性冲突
绿色框圈住的两个属性冲突

Object.defineProperty中的 get方法 获取对象属性值时,会被调用; set方法给对象属性赋值时,会被调用

<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>

 
<body>
<!-- MVVM:双向数据绑定,数据影响视图,视图影响数据
           angular 脏值检测 
           vue 数据劫持+发布订阅模式
-->
<!-- vue不兼容ie8及以下版本  Object.defineProperty -->
</body>
<script>
    let obj = {}
                             //key
    Object.defineProperty(obj,"school",{
        configurable:true,//配置,使属性可删除
        //writable:true,//配置,使属性可修改
        enumerable:true,//配置,是属性可枚举
        //value:'qhbd',//默认值,school:qhbd
        get(){//代替value,默认值 获取对象属性值时,会被调用
            return 'qhbd'
        },
        set(val){//给对象属性赋值时,会被调用
            console.log(val+'我被调用了')
        }
    })
    console.log(obj) //{school:"qhbd"}
</script>
</html>