class

今天把es6中的class进行了整理,


function Car () {
  this.fuel = 0;
  this.distance = 0;
}

Car.prototype.move = function () {
  if (this.fuel < 1) {
    throw new RangeError('Fuel tank is depleted')
  }
  this.fuel--
  this.distance += 2
}

Car.prototype.addFuel = function () {
  if (this.fuel >= 60) {
    throw new RangeError('Fuel tank is full')
  }
  this.fuel++
}

相当于


class Car {
  constructor () {
    this.fuel = 0
    this.distance = 0
  }
  move () {
    if (this.fuel < 1) {
      throw new RangeError('Fuel tank is depleted')
    }
    this.fuel--
    this.distance += 2
  }
  addFuel () {
    if (this.fuel >= 60) {
      throw new RangeError('Fuel tank is full')
    }
    this.fuel++
  }
}

//注意中间没有逗号。

同样也增加了继承


class Tesla extends Car {
  move () {
    super.move()
    this.distance += 4
  }
}

静态方法


class Car {
  constructor () {
    this.topSpeed = Math.random()
  }
  static isFaster (left, right) {
    return left.topSpeed > right.topSpeed;
  }
}

var a = new Car();
var b = new Car();
console.log(Car.isFaster(a,b));

类的prototype属性和proto属性

大多数浏览器的ES5实现之中,每一个对象都有proto属性,指向对应的构造函数的prototype属性。Class作为构造函数的语法糖,同时有prototype属性和proto属性,因此同时存在两条继承链。

(1)子类的proto属性,表示构造函数的继承,总是指向父类。

(2)子类prototype属性的proto属性,表示方法的继承,总是指向父类的prototype属性。


class A {}
class B extends A {}
B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 9,569评论 3 11
  • class声明 class 是 ES6 模仿面向对象语言(C++, Java)提出的定义类的方法。形式类似 C++...
    faremax阅读 1,756评论 0 0
  • 1.构造函数,原型,实例之间的关系 每个构造函数都有一个原型对象(prototype属性),原型对象都包含一个指向...
    秦小婕阅读 4,318评论 0 0
  • 基本用法 Class之间可以通过extends关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多...
    庸者的救赎阅读 3,180评论 0 2
  • 咖啡馆,有你的爱人 儿童乐园,有你的宝贝 想你所想、爱你所爱 才能同行到更远方
    禾花花阅读 1,634评论 0 0

友情链接更多精彩内容