ES6新特性:类和继承
类 & 继承
类也是 ES6 一个不可忽视的新特性,虽然只是句法上的语法糖,但是相对于 ES5,学习 ES6 的类之后对原型链会有更加清晰的认识。
特性
- 本质为对原型链的二次包装
- 类没有提升
- 不能使用字面量定义属性
- 动态继承类的构造方法中 super 优先 this
类的定义
/* 类不会被提升 */ let puppy = new Animal('puppy'); // => ReferenceError class Animal { constructor(name) { this.name = name; } sleep() { console.log(`The ${this.name} is sleeping...`); } static type() { console.log('This is an Animal class.'); } } let puppy = new Animal('puppy'); puppy.sleep(); // => The puppy is sleeping... /* 实例化后无法访问静态方法 */ puppy.type(); // => TypeError Animal.type(); // => This is an Animal class. /* 实例化前无法访问动态方法 */ Animal.sleep(); // => TypeError /* 类不能重复定义 */ class Animal() {} // => SyntaxError
以上我们使用 class 关键字声明了一个名为 Animal 的类。
虽然类的定义中并未要求类名的大小写,但鉴于代码规范,推荐类名的首字母大写。
两点注意事项:
- 在类的定义中有一个特殊方法 constructor(),该方法名固定,表示该类的构造函数(方法),在类的实例化过程中会被调用(new Animal('puppy'));
- 类中无法像对象一样使用 prop: value 或者 prop = value 的形式定义一个类的属性,我们只能在类的构造方法或其他方法中使用 this.prop = value 的形式为类添加属性。
最后对比一下我们之前是怎样写类的:
function Animal(name) { this.name = name; } Animal.prototype = { sleep: function(){ console.log('The ' + this.name + 'is sleeping...'); } }; Animal.type = function() { console.log('This is an Animal class.'); }
class 关键字真真让这一切变得清晰易懂了~
类的继承
class Programmer extends Animal { constructor(name) { /* 在 super 方法之前 this 不可用 */ console.log(this); // => ReferenceError super(name); console.log(this); // Right! } program() { console.log("I'm coding..."); } sleep() { console.log('Save all files.'); console.log('Get into bed.'); super.sleep(); } } let coder = new Programmer('coder'); coder.program(); // => I'm coding... coder.sleep(); // => Save all files. => Get into bed. => The coder is sleeping.
这里我们使用 class 定义了一个类 Programmer,使用 extends 关键字让该类继承于另一个类 Animal。
如果子类有构造方法,那么在子类构造方法中使用 this 对象之前必须使用 super() 方法运行父类的构造方法以对父类进行初始化。
在子类方法中我们也可以使用 super 对象来调用父类上的方法。如示例代码中子类的 sleep() 方法:在这里我们重写了父类中的 sleep() 方法,添加了两条语句,并在方法末尾使用 super 对象调用了父类上的 sleep() 方法。
俗话讲:没有对比就没有伤害 (*゜ー゜*),我们最后来看一下以前我们是怎么来写继承的:
function Programmer(name) { Animal.call(this, name); } Programmer.prototype = Object.create(Animal.prototype, { program: { value: function() { console.log("I'm coding..."); } }, sleep: { value: function() { console.log('Save all files.'); console.log('Get into bed.'); Animal.prototype.sleep.apply(this, arguments); } } }); Programmer.prototype.constructor = Programmer;
如果前文类的定义中的前后对比不足为奇,那么这个。。。
给你一个眼神,自己去体会 (⊙ˍ⊙),一脸懵逼.jpg

浙公网安备 33010602011771号