读取
在读取操作中,若是子对象没有同名属性,若使用读取函数后,将读到父对象的属性,若子对象有同名属性,读取函数将读取自己的属性
let father = {
name: "father",
Print() {
alert(this.name);
},
Set(value){
this.name = value;
}
};
let children = {
// name: "children",
__proto__: father
}
children.Print(); //father
children.Set("glh");
father.Print(); //father
children.Print(); //glh
let father = {
name: "father",
Print() {
alert(this.name);
},
Set(value){
this.name = value;
}
};
let children = {
name: "children",
__proto__: father
}
children.Print(); //children
father.Print(); //father
写入操作
在用子对象执行继承来的写入操作时,若有this,该this是面向的点号之前的对象,因此若子对象无该属性会创建一个同名属性
let father = {
name: "father",
Print() {
alert(this.name);
},
Set(value){
this.name = value;
}
};
let children = {
__proto__: father
}
children.Print(); //father
children.Set("children"); //此时this是面向children的 因此在children创建同名属性 值为children
children.Print(); //children
father.Print();//father
let father = {
name: "father_name",
surname: "father_surname",
set fullName(value) {
[this.name, this.surname] = value.split(" ");
},
get fullName() {
return `${this.name} ${this.surname}`;
}
};
let children = {
__proto__: father,
};
alert(children.fullName); //father_name father_surname;
children.fullName = "Alice Cooper"; //this面向的是children,在children中创建这2个属性 并赋值
alert(children.fullName); //Alice Cooper
alert(father.fullName);//father_name father_surname;
遍历操作
Object.keys 只返回自己的 key
for…in 会遍历自己以及继承的键,若不想打印输出继承的键值
let animal = {
eats: true,
};
let rabbit = {
jumps: true,
__proto__: animal
};
for (let prop in rabbit) {
let isOwn = rabbit.hasOwnProperty(prop);
if (isOwn) {
alert(`Our: ${prop}`); // Our: jumps
} else {
alert(`Inherited: ${prop}`); // Inherited: eats
}
}