<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// Object.defineProperty 这个方法在为对象添加或者修改 属性为响应式属性
let obj = {
firstName:'zhao',
lastName:'liying'
}
// obj.fullName = 'zhao-liying'
// console.log(obj)
// obj.firstName = 'liu'
// console.log(obj)
// obj.fullName = 'liu-yifei'
// console.log(obj)
Object.defineProperty(obj,'fullName',{
get(){
// 当访问对象的fullName属性的时候
return this.firstName + '-' + this.lastName
},
set(val){
// 当设置对象的fullName属性的时候
let arr = val.split('-')
this.firstName = arr[0]
this.lastName = arr[1]
}
})
console.log(obj.fullName)
obj.fullName = 'liu-yifei'
console.log(obj)
// 模拟数据代理
let vm ={}
let data = {msg:'zhaoliyin'}
Object.defineProperty(vm,'msg',{
get(){
return data.msg
},
set(val){
data.msg = val
}
})
console.log(vm.msg)
vm.msg = '嘿嘿'
console.log(vm.msg)
console.log(data)
</script>
</body>
</html>