JS高级----对象的继承


什么是继承?

一个对象继承另一个对象,可以使用父级对象的属性和方法,共享资源,避免大量浪费系统资源


prototype 属性的作用:

  • 原型对象的所有属性和方法,都能被实例对象共享。

  • 如果属性和方法定义在原型上,那么所有实例对象就能共享,不仅节省了内存,还体现了实例对象之间的联系。

        function Person() {

        }
        Person.prototype.eyes = 2;
        p1 = new Person();

        console.log(p1.eyes);

在这里插入图片描述


原型链:

  • 所有对象都有自己的原型对象
  • 原型对象也是对象,它也有自己的原型
  • 对象的原型最终都可以上溯到Object.prototype
  • Object.prototype的原型为null,原型链的尽头就是Object.prototype

prototype指向上一级原型对象

        function Person() {

        }

        function Student() {

        }

        p1 = new Person();
        s1 = new Student();
        console.log(Person.prototype);
        console.log(Student.prototype);

在这里插入图片描述


constructor 属性:

  • prototype对象都有constructor属性,指向prototype对象所在的构造函数
  • constructor属性可以知道某一个实例对象来自于哪个函数
     function Person() {

        }
        console.log(Person.prototype);
        console.log(Person.prototype.constructor);
        console.log(Person.prototype.constructor === Person);

在这里插入图片描述


构造函数的继承:

  1. 使用call()方法继承:
        function Person() {
            this.eyes = 2;
            this.legs = 2;
        }

        function Doctor() {
            Person.call(this);
        }
        // 如果直接子类的原型 = 父类的原型 子类的原型还是为Object
        // Doctor.prototype = Person.prototype

        Doctor.prototype = Object.create(Person.prototype);
        Doctor.prototype.constructor = Doctor;
        d1 = new Doctor();

        console.log(d1.eyes);
        // 要修改子类的prototype指向父类的原型 
        // 如果不把子类的原型指向父类的原型  子类的prototype还是指向Object
        // 但是可以调用父类的方法
        console.log(Person.prototype);
        console.log(Doctor.prototype);
        // 还要修改子类的prototype对象的constructor属性的指向
        console.log(Person.prototype.constructor);
        console.log(Doctor.prototype.constructor);

在这里插入图片描述

  1. 子类的prototype对象 = new 父类(); 继承
      function Person() {
            this.eyes = 2;
            this.legs = 2;
            this.study = function() {
                console.log('学习');

            }
        }

        function Doctor() {


        }

        // 子类的prototype对象  =  父类的一个对象
        Doctor.prototype = new Person();
        // 修改子类prototype对象的constructor属性为自身
        Doctor.prototype.constructor = Doctor;
        d1 = new Doctor();
        console.log(d1.eyes);
        d1.study();
        console.log(Person.prototype);
        console.log(Doctor.prototype);
        console.log(Person.prototype.constructor);
        console.log(Doctor.prototype.constructor);

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值