JavaScript(三)继承的问题

JavaScript(三)继承的问题

读取

在读取操作中,若是子对象没有同名属性,若使用读取函数后,将读到父对象的属性,若子对象有同名属性,读取函数将读取自己的属性

        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
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值