大家都晓得vue3.0之前的双向绑定原理就是靠defineProperty()办法,那么它有什么神奇之处呢?
1.根底介绍
Object.defineProperty(obj, prop, descriptor)
1.它承受三个参数,而且都是必填的。
- obj :要定义属性的对象。指标对象
- prop:第二个参数:须要定义的属性或办法的名字。
- descriptor:要定义或批改的属性描述符。 属性的形容对象
例:
var obj = {}
Object.defineProperty(obj,"say",{
value:"点赞"
});
console.log( obj.say); //'点赞'
2.descriptor
descriptor是defineProperty的第三个参数,个别被叫做属性形容对象。
取值:
Object.defineProperty(obj,"newKey",{
value:"hello",
writable:false,
enumerable:false,
configurable:false,
set:function(){},
get:function(){},
});
先介绍前四个属性。
- value:属性的值。
- writable:属性的值是否能够被重写。设置为true能够被重写;设置为false,不能被重写。
- enumerable:此属性是否能够被枚举(应用for…in或Object.keys())。设置为true能够被枚举;false则不能被枚举。
- configurable:是否能够删除指标属性或是否能够再次批改属性的个性(writable, configurable, enumerable)。设置为true能够被删除或能够从新设置个性;设置为false,不能被能够被删除或不能够从新设置个性。
留神:如果你只设置了value和值,其余的默认的取值都是false
var a= {}
Object.defineProperty(a,"b",{
value:123
})
console.log(a.b);//123
相当于
var a= {}
Object.defineProperty(a,"b",{
value:123,
writable:false,
enumerable:false,
configurable:false
})
console.log(a.b);//123
最初来看最要害的,也是和vue双向绑定间接相干的。
let a = {}; let c;
Object.defineProperty(a, 'b', {
set(newVal){ console.log('设置的值是'+newVal); c=newVal } ,
get(){ console.log('读取了b属性的值:'); return c}
});
console.log(a.b); //读取了b属性的值: undefined
a.b=9; //设置的值是9
console.log(a.b); //读取了b属性的值: 9
最初重头戏来了哦。用defineProperty实现双向绑定。
上代码:
<html>
<head></head>
<body>
<div></div>
<input type="text">
<script>
let obj = {};
function bind(obj,name,callback){
Object.defineProperty(obj,name,{
set(newval){
value = newval;
callback(value); //*执行assignment,把值同时放入input和div中
},
get(){
return value;
}
});
};
bind(obj,'inputVal',assignment); //先执行的是这个
function assignment(value){
document.querySelector('div').innerHTML = value;
document.querySelector('input').value = value;
}
document.querySelector('input').addEventListener('input',(e) => {
obj['inputVal'] = e.target.value; //会触发defineProperty的set办法
});
</script>
</body>
</html>
0k,本文到此结束。最初揭示,请看下自己的昵称
发表回复