es6中的class

来源:互联网 发布:互联网十云计算概念股 编辑:程序博客网 时间:2024/06/05 05:04

js中的类

之前在javascript没有类这样的概念,而是构造函数来定义某一种有着相似属性的“类”。然后通过new 运算符来获得该”类”的实例,通过原型链来继承它的父类的属性和方法。

//构造函数function Point(x, y) {  this.x = x;  this.y = y;}Point.prototype.toString = function () {  return '(' + this.x + ', ' + this.y + ')';};//实例var p = new Point(1, 2);

上面的代码用 ES6 的class改写,就是下面这样。

//定义类class Point {  constructor(x, y) {    this.x = x;    this.y = y;  }  toString() {    return '(' + this.x + ', ' + this.y + ')';  }}注意,定义“类”的方法的时候,前面不需要加上`function`这个关键字,直接把函数定义放进去了就可以了。另外,方法之间不需要逗号分隔,加了会报错。

class语法糖

基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

//使用class构造函数的使用class Bar {  doStuff() {    console.log('stuff');  }}var b = new Bar();b.doStuff() // "stuff"
//构造函数的`prototype`属性,在 ES6 的“类”上面继续存在。事实上,类的所有方法都定义在类的`prototype`属性上面。class Point {  constructor() {    // ...  }  toString() {    // ...  }  toValue() {    // ...  }}// 等同于Point.prototype = {  constructor() {},  toString() {},  toValue() {},};//在类的实例上面调用方法,其实就是调用原型上的方法。class B {}let b = new B();b.constructor === B.prototype.constructor // true

class的继承

通过关键字 extends 来继承一个类,并且,可以通过 super 关键字来引用父类。

class People {    constructor(name) { //构造函数          this.name = name;    }    sayName() {          console.log(this.name);    }}class Student extends People {    constructor(name, grade) { //构造函数        super(name);    //调用父类构造函数          this.grade = grade;    }    sayGrade() {          console.log(this.grade);    }}
//class.extend继承的本质还是prototyextend = function(destination, source) {             for (var property in source) {            destination[property] = source[property];          }          return destination;    };

参考阮一峰的es6教程

原创粉丝点击