function getXH() {
let xiaohong = {
name: {
first: '小红', 'last': '章'
},
age: 15
};
let keys = Object.keys(xiaohong);
newXiaohong = new Proxy(xiaohong, {
get(target, key) {
let result = target[key];
//如果是获取 年龄 属性,则添加 岁字
if (key === "age") result += "岁";
return result;
},
set(target, key, value) {
debugger
if (key === "age" && typeof value !== "number") {
throw Error("age字段必须为Number类型");
}
if (keys.includes(key)) {
console.error("不能修改属性");
} else {
target[key] = value;
}
// return Reflect.set(target, key, value);
}
});
return newXiaohong;
}
const xiaohong = getXH()
// console.log(`我叫${xiaohong.name} 我今年${xiaohong.age}了`);
// xiaohong.age = 12;
xiaohong.name.age = 11;
console.log(xiaohong)
console