ES6中class的实现

在es6出来之后,我们看到js终于有class这个关键字,表示我们终于可以使用官方的类了。那么es6的类和之前的我们使用原型链继承实现的类有什么联系么。

答案是一模一样

JavaScript classes introduced in ECMAScript 2015 are syntactical sugar over JavaScript’s existing prototype-based inheritance. (在 ECMAScript 6 引入的 JavaScript 类(class)是 JavaScript 现有的原型继承的语法糖。) —— MDN Classes

好吧,那么为了使我们更好的理解es6的class,也是倒过来更好的理解js的原型链,下面我们把类的es6写法和原型链实现的写法一一列出

类的创建,类的构造器和原型方法

ES6

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

  calcArea() {
    return this.height * this.width;
  }
}
const square = new Polygon(10, 10);

// 100
console.log(square.area);

原型链

var Polygon = function(height, width){
    this.height = height;
  this.width = width;
}

Polygon.prototype.calcArea = function() {
    return this.height * this.width;
}

类的静态方法

static关键字用来定义类的静态方法。静态方法是指那些不需要对类进行实例化,使用类名就可以直接访问的方法,需要注意的是静态方法不能被实例化的对象调用。静态方法经常用来作为工具函数。
ES6

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);
    }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);

console.log(Point.distance(p1, p2));

原型链

var Point = function(x, y){
  this.x = x;
  this.y = y;
}

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

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

至此我们也可以明白了如何用原型链去构建一个类

其实当我们去查看babel对于类的实现,其实也是一样的

var _createClass = function() {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor) descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor); 
    } 
  }
  return function(Constructor, protoProps, staticProps) {
    //实例方法(原型方法)的实现
    if (protoProps) defineProperties(Constructor.prototype, protoProps);
    //静态函数的实现
    if (staticProps) defineProperties(Constructor, staticProps);
    return Constructor; 
  };
}();

类的继承

未完

参考文档
Javascript原型链
MDN Classes

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值