1、回顾Object.defineProperty
<!DOCTYPE html>
<html lang="en" xmlns:v-model="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>数据代理,回顾 Object.defineProperty</title>
</head>
<body>
<script type="text/javascript">
let person = {
name:'张三',
sex:'男',
age:18
};
console.log(Object.keys(person));
for (let key in person){
console.log('@',person[key])
}
console.log(person);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:v-model="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>数据代理,回顾 Object.defineProperty</title>
</head>
<body>
<script type="text/javascript">
let person = {
name:'张三',
sex:'男',
//age:18
};
Object.defineProperty(person,'age',{
value:18
});
console.log(Object.keys(person));
for (let key in person){
console.log('@',person[key])
}
console.log(person);
</script>
</body>
</html>
enumerable :true 控制属性是否可以枚举,默认值是false
Object.defineProperty(person,'age',{
value:18,
enumerable:true,//控制属性是否可以枚举,默认值是false
});
writable:true, 控制属性是否可以修改。默认值是false
Object.defineProperty(person,'age',{
value:18,
enumerable:true,//控制属性是否可以枚举,默认值是false
writable:true, // 控制属性是否可以修改。默认值是false
});
configurable:true,//控制属性是否可以被删除 ,默认是false
Object.defineProperty(person,'age',{
value:18,
enumerable:true,//控制属性是否可以枚举,默认值是false
writable:true, // 控制属性是否可以修改。默认值是false
configurable:true,//控制属性是否可以被删除 ,默认是false
});
getter 函数使用
<!DOCTYPE html>
<html lang="en" xmlns:v-model="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>数据代理,回顾 Object.defineProperty</title>
</head>
<body>
<script type="text/javascript">
let number = 18;
let person = {
name:'张三',
sex:'男',
};
Object.defineProperty(person,'age',{
//当有人读取person的age属性是,get函数(getter)就会被调用,且返回值就是age的值
get:function () {
return number
}
});
console.log(Object.keys(person));
for (let key in person){
console.log('@',person[key])
}
console.log(person);
</script>
</body>
</html>
Object.defineProperty(person,'age',{
//当有人读取person的age属性是,get函数(getter)就会被调用,且返回值就是age的值
get() {
return number
}
});
setter 函数使用
<!DOCTYPE html>
<html lang="en" xmlns:v-model="http://www.w3.org/1999/xhtml" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>数据代理,回顾 Object.defineProperty</title>
</head>
<body>
<script type="text/javascript">
let number = 18;
let person = {
name:'张三',
sex:'男',
};
Object.defineProperty(person,'age',{
//当有人读取person的age属性是,get函数(getter)就会被调用,且返回值就是age的值
get() {
console.log('有人读取age属性了');
return number
},
//当有人修改person的age属性时。set(setter)就会被调用 且会收到修改的具体值
set:function(value){
console.log('有人修改了age的值,且值是',value);
number = value;
}
});
console.log(Object.keys(person));
for (let key in person){
console.log('@',person[key])
}
console.log(person);
</script>
</body>
</html>
数据代理:通过一个对象代理对另外一个对象属性操作(读/写)