不知道你在使用Vue的时候有没有想过,为何定义在data
对象中的属性,能够用Vue
的实例this
进行访问?bash
咱们来看看源码的实现。markdown
var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; // 源码中是这样调用的:proxy(vm, '_data', key) // vm是Vue的实例,key是data对象属性的名字 function proxy (target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter () { return this[sourceKey][key] }; sharedPropertyDefinition.set = function proxySetter (val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } 复制代码
好比有个以下demoapp
const vm = new Vue({ el: '#app', data: { message: 'Hello Vue!' }, created() { console.log(this.message) // 输出Hello Vue! console.log(this._data.message) // 一样输出Hello Vue! } }) 复制代码
也就是说当咱们这样this.message
写的时候,Vue
经过Object.defineProperty
给this.message
设置一层代理,实际访问的是this._data
里的message
属性,而this._data
指向的对象就是咱们写的data
对象。oop