深入Vue实现原理
跟着大佬撸原理
https://www.jianshu.com/p/123146abdd1a
自己总结:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<div> <input type="text" id="input-msg"> <p id="output-msg"></p> </div> <script> var inputMsg = document.getElementById('input-msg'); var outputMsg = document.getElementById('output-msg'); var obj = { msg: 'hello' }; var key = 'msg'; var val = obj[key]; Object.defineProperty(obj, 'value', { enumerable: true, configurable: true, set: function (newValue) { val = newValue; outputMsg.innerHTML = val; console.log('setter',val); console.log('setter',obj); }, get: function () { console.log('getter',val); return val; } }) inputMsg.addEventListener('input',function(e){ obj['value'] = e.target.value; console.log(e.target.value) }) console.log(obj) </script>
上面的Object.defineProperty监听obj的value,当在控制台打印obj.value的时候会走到get方法里面,当给obj.value = 2的时候,会走到set方法里面;