使用es6的class方法来实现继承

1,class了解

在es6之前,js实现继承都是通过prototype(原型链)的方式来实现的,

原型继承参考 https://blog.csdn.net/weixin_43322208/article/details/89349703

在es6出现之后,可以通过class来实现继承。
用新的class关键字来编写以往的构造函数,可以这样写:

//构造函数写法
function Student(name) {
    this.name = name;
}

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

//class写法
class Student {
    constructor(name) {
        this.name = name;
    }

    hello() {
        alert('Hello, ' + this.name + '!');
    }
}

var xiaoming = new Student('小明');
xiaoming.hello();

class的定义包含了构造函数constructor和定义在原型对象上的函数hello()(注意没有function关键字),这样就避免了Student.prototype.hello = function () {…}这样分散的代码。

2,class继承

用class定义对象的另一个巨大的好处是继承更方便了使用extends。创建一个PrimaryStudent 继承上方的Student构造函数

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

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

extends则表示原型链对象来自Student

ES6引入的class和原有的JavaScript原型继承有什么区别呢?实际上它们没有任何区别,class的作用就是让JavaScript引擎去实现原来需要我们自己编写的原型链代码。简而言之,用class的好处就是极大地简化了原型链代码。

缺点:
因为不是所有的主流浏览器都支持ES6的class(IE目前都不支持)。如果一定要现在就用上,就需要一个工具把class代码转换为传统的prototype代码,可以试试Babel这个工具

参考链接:https://www.liaoxuefeng.com/wiki/1022910821149312/1072866346339712

发布了88 篇原创文章 · 获赞 13 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/yiyueqinghui/article/details/104804678