005|JavaScript ES6新特性之Classes

在过去,需要像 053|JavaScript 继承详解 那样实现继承。JavaScript这种继承实现方式与其它面向对象编程语言有着巨大的区别,本质上是将最原始的继承实现暴露给了开发者。

ES6中,JavaScript提供了像其它面向对象编程语言类似的语法,class语法。class语法并没有必变JavaScript使用原型链实现继承的本质,它只是一种语法糖。使用class这种语法糖,在继承的实现上更加的简单、清晰。

下面定义了一个名为Rectangle的类:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

class语法声明的类没有声明前置(hoisting)。如,下面代码会引发错误:

var p = new Rectangle(); // ReferenceError

class Rectangle {}

class也可以赋给一个变量,这种语法叫class表达式:

// unnamed
var Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

// named
var Rectangle = class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};

constructor即是构造函数,每个class中只能有一个constructor。
使用super关键字,可以调用父类构造函数。

class Cat { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Lion extends Cat {
  speak() {
    super.speak();
    console.log(this.name + ' roars.');
  }
}

class中也可以定义get方法:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  
  get area() {
    return this.calcArea();
  }

通过 static 方法定义静态方法:

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;

    return Math.sqrt(dx*dx + dy*dy);
  }
}

最关键的来了,如何实现继承?通过 extends关键字即可。

class Animal { 
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    console.log(this.name + ' makes a noise.');
  }
}

class Dog extends Animal { // 使用extends实现继承
  speak() {
    console.log(this.name + ' barks.');
  }
}

var d = new Dog('Mitzie');
d.speak(); // Mitzie barks.

经典语法和es6 class语法可以混用:

function Animal (name) {
  this.name = name;  
}

Animal.prototype.speak = function () {
  console.log(this.name + ' makes a noise.');
}

class Dog extends Animal {
  speak() {
    console.log(this.name + ' barks.');
  }
}

var d = new Dog('Mitzie');
d.speak(); // Mitzie barks.

完。

什么是Spread Operator?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 4,145评论 3 11
  • 官方中文版原文链接 感谢社区中各位的大力支持,译者再次奉上一点点福利:阿里云产品券,享受所有官网优惠,并抽取幸运大...
    HetfieldJoe阅读 3,675评论 2 27
  • 一、ES6简介 ​ 历时将近6年的时间来制定的新 ECMAScript 标准 ECMAScript 6(亦称 ...
    一岁一枯荣_阅读 6,135评论 8 25
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,867评论 18 399
  • 在上体育课,太阳依旧的炎热,似乎有种要把人烤化的感觉。坐在体育馆的我心情也是不知如何来形容。今天要体育考试,我报的...
    鹿先森idle阅读 226评论 0 0