共计 1798 个字符,预计需要花费 5 分钟才能阅读完成。
大家都晓得 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, 本文到此结束。最初揭示,请看下自己的昵称
正文完