JS中的继承

原型继承

实现思路:子类的原型指向父类的一个实例。使子函数的prototype = new 父函数(子类中创建父类的实例)

function parent() {
    this.name = "lisi";
    this.age = 18;
    this.getName = function () {
        console.log(this.age + "岁的" + this.name);
    }

    function getAge(){
        console.log(this.age);
    }
}

function child() {
    this.hobby = 'eat';
}
child.prototype = new parent();//主要
var lisi = new child();
console.log(lisi.hobby); //eat
lisi.getName(); // "18岁的lisi"
console.log(lisi.age); //18
lisi.getAge()//报错

构造继承

实现思路:子函数中调用父函数是.call方法

function parent() {
    this.name = "lisi";
    this.age = 18;
    this.getName = function () {
        console.log(this.age + "岁的" + this.name);
    }
}

function child() {
    this.hobby = 'eat';
    parent.call(this)
}
var lisi = new child();
console.log(lisi.hobby); //eat
lisi.getName(); // "18岁的lisi"
console.log(lisi.age); //18

两种方法对某个子实例修改属性都不会影响其他子实例

组合继承(组合原型链继承和借用构造函数继承)(常用)

class继承

父类

class Student {
    constructor(name) {
        this.name = name;
    }
    hello() {
        alert('Hello, ' + this.name + '!');
    }
}

子类

class PrimaryStudent extends Student {
    constructor(name, grade) {
        super(name); // 记得用super调用父类的构造方法!
        this.grade = grade;
    }

    myGrade() {
        alert('I am at grade ' + this.grade);
    }
}

需要通过super(name)来调用父类的构造函数,否则父类的name属性无法正常初始化。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值