new Vue({
el: '#app',
data: {
message: 'this is message';
}
})
在编写代码中可以通过this.message
访问到message
的值,这不是魔法,直接上源码。
在state.js
的initData
中,有如下代码
function initData(vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
/**** 此处省略若干行 ****/
// 通过proxy把data里的值代理到vm对象上
proxy(vm, `_data`, key)
}
// proxy函数相关的代码
// 定义访问器属性
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
function proxy (target: Object, sourceKey: string, key: string) {
sharedPropertyDefinition.get = function proxyGetter() {
return this[sourceKey][key]; // 即访问 this['_data'][key]
}
sharedPropertyDefinition.set = function proxySetter(val) {
this[sourceKey][key] = val;
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
通过Object.defineProperty
把data上的属性代理到vm
上,vm
即this对象
。
这就是可以通过this.message
访问data
属性的原因。