JS高级面向对象(三)-构造函数的继承

三,构造函数的继承

ES6之前并没有 extends 继承,我们之前都是通过 构造函数 + 原型对象 模拟继承,被称为组合继承

1,call方法使用

  • call()
    使用
    // call方法
    function fn(x, y) {
        console.log(x + y);
        console.log('this的指向:', this);
    }
    var a = {
        name: 'xyb',
        age: 20
    }
    // 1. call方法可以调用函数
    fn.call(null, 1, 2); // this的指向: Window {po....}
    // 2. call方法可以改变this的指向
    fn.call(a, 1, 2); //this的指向: {name: "xyb", age: 20}
    

2,继承属性

  • 通过 call() 方法,在子构造函数里面调用父构造函数,并改变 this 指向

    // 1. 父构造函数
    function Father(name, age) {
        this.name = name;
        this.age = age;
    }
    // 2. 子构造函数
    function Son(name, age) {
        // 把之后父构造函数中的this改变成son的this指向
        Father.call(this, name, age)
    }
    
    var xyb = new Son('xyb', 20);
    console.log(xyb); // Son {name: "xyb", age: 20}
    

3,继承方法

  1. 错误的写法

    // 1. 父构造函数
    function Father(name, age) {
        this.name = name;
        this.age = age;
    }
    Father.prototype.say = function() {
        console.log('能说话');
    }
    // 2. 子构造函数
    function Son(name, age) {
        Father.call(this, name, age);
    }
    Son.prototype = Father.prototype; // 错误的写法,和父亲的原型对象是同一个,一个修改都会修改
    
    var xyb = new Son('xyb', 20);
    Son.prototype.haha = function() {};
    console.log(Father.prototype);  // {say: ƒ, haha: ƒ, constructor: ƒ} 父亲的也被修改了!!
    
  2. 正确的写法

    // 1. 父构造函数
    function Father(name, age) {
        this.name = name;
        this.age = age;
    }
    Father.prototype.say = function() {
        console.log('能说话');
    }
    // 2. 子构造函数
    function Son(name, age) {
        Father.call(this, name, age);
    }
    Son.prototype = new Father(); // 重新new一块新的Father空间,这样就能和Father构造函数的原型隔离
    Son.prototype.constructor = Son;
    var xyb = new Son('xyb', 20);
    console.log(xyb.__proto__.constructor); // 构造函数指回Son
    

    在这里插入图片描述

4,类的本质

类的本质就是,构造函数的另外一种写法,是构造函数的语法糖

构造函数的特点:

  1. 构造函数的原型对象是 prototype

  2. 构造函数的原型里面有一个 constructor 构造函数,指回构造函数

  3. 构造函数可以通过原型 prototype 添加方法

  4. 构造函数的实例有 __proto__ 属性,并且指向构造函数的原型对象上

    class Peopel {
        constructor(name, age) {
            this.name = name
            this.age = age;
        };
        sing() {
            console.log('唱歌了');
        }
    }
    var a = new Peopel('xyb', '20');
    console.log(typeof Peopel); // function, 本质上是一个函数
    console.log(a.__proto__); // {constructor: ƒ, sing: ƒ} 有一个构造函数和方法
    console.log(Peopel.prototype); // {constructor: ƒ, sing: ƒ}
    console.log(a.__proto__ === Peopel.prototype); // true
    console.log(a.__proto__.constructor); // 类本身
    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值