Class

ES6新特征 - Class

本节主要介绍了ES6新特征中Class的基本用法与属性方法,介绍了Class继承的基本用法。

2021-01-25侠课岛    初级拔高       

前端/前端/前端系列课程P2 15     0     1621

(六十四)ES6新特征 - Class

1:基本概念

  • 构造函数语法糖

    • 更加清晰的写法
    • 面向对象编程
  function Position(x, y) {
    this.x = x;
    this.y = y;
  }

  const position = new Position(1, 1);
  class Position {
    constructor(x, y) {
      this.x = x;
      this.y = y;
    }
  }
  Position === Position.prototype.constructor;
  /* true */
  const position = new Position(1, 1);
  • 类的所有方法定义在类的prototype属性
  class Position {
    constructor(x, y) {
      this.x = x;
      this.y = y;
    }

    scan() {
      console.log(this.x, this.y);
    }
  }

  Position.prototype;
  /*
  {
    constructor: class Position
    scan: ƒ scan()
    __proto__: Object
  }
  */
  • 内部方法不可枚举
  class Position {
    constructor(x, y) {
      this.x = x;
      this.y = y;
    }

    scan() {
      console.log(this.x, this.y);
    }
  }

  Object.keys(Position.prototype);
  /* [] */
  Object.getOwnPropertyNames(Position.prototype);
  /* ["constructor", "scan"] */
  • this指向 - 默认指向实例本身
  class Position {
    constructor(x, y) {
      this.x = x;
      this.y = y;
    }

    scan() {
      console.log(this.x, this.y);
    }
  }

  const position = new Position(1, 1);
  const { scan } = position;
  scan();
  /* Cannot read property 'x' of undefined */
  class Position {
    constructor(x, y) {
      this.x = x;
      this.y = y;
      this.scan = this.scan.bind(this);
    }
    scan() {
      console.log(this.x, this.y);
    }
  }

  const position = new Position(1, 1);
  const { scan } = position;
  scan();
  /* 1 1 */
  class Position {
    constructor(x, y) {
      this.x = x;
      this.y = y;
    }
    scan = () => {
      console.log(this.x, this.y);
    }
  }

  const position = new Position(1, 1);
  const { scan } = position;
  scan();
  /* 1 1 */

本教程图文或视频等内容版权归侠课岛所有,任何机构、媒体、网站或个人未经本网协议授权不得转载、转贴或以其他方式复制发布或发表。

评价

15

本课评分:
  •     非常好
难易程度:
  •     适中的

内容目录


本文索引

本文标签


|
教程
粉丝
主页

签到有礼

已签到2天,连续签到7天即可领取7天全站VIP

  • 1
    +2 金币
  • 2
    +3 金币
  • 3
    +5 金币
  • 6
    +7 金币
  • 5
    +6 金币
  • 4
    暖心福利
    自选分类VIP ×1天
  • 7
    惊喜大礼

    自选分类VIP ×3天 +20金币
  • 持续签到 +8 金币

金币可以用来做什么?