AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
在ES5的时候,生成实例对象的方式是通过构造函数,如下: ``` function Student (name, age){ this.name = name; this.age = age; } Student.prototype.study = function () { console.log("做作业"); } var s = new Student("小明",8); s.study(); ``` ES6 引入了 Class(类)这个概念,作为对象的模板。基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到。新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。所以上面的示例换成ES6的写法就是: ``` class Student { constructor(name, age){ this.name = name; this.age = age; } study () { console.log("做作业"); } } let s = new Student("小明",8); s.study(); ``` 而在继承方面,ES5是采用了原型链继承的方式,示例如下: ``` function SmallStudent(name,age) { Student.call(this,name,age); this.playGame = function () { console.log("玩游戏"); } } SmallStudent.prototype = new Student(); ``` 显然这种方式不是很好理解,所以ES6中可以通过extends关键字来实现继承就好理解多了。如下: ``` class SmallStudent extends Student{ //SmallStudent 继承自 Student constructor(name,age,sex){ //继承的子类没有自己的this super(name,age);//调用父类的构造方法 this.sex = sex; } study (){ return super.study()+"抄了50遍听写"; } playGame () { console.log("玩游戏"); } } ``` 最后,父类的静态方法,也会被子类继承。