详解defineProperty,并手动实现双向绑定

119 阅读2分钟

大家都知道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(){},
});

先介绍前四个属性。

  1. value:属性的值。
  2. writable:属性的值是否可以被重写。设置为true可以被重写;设置为false,不能被重写。
  3. enumerable:此属性是否可以被枚举(使用for...in或Object.keys())。设置为true可以被枚举;false则不能被枚举。
  4. 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,本文到此结束。最后提醒,请看下本人的昵称