面向对象编程

演讲者:交互开发课题组

内容提纲

  1. ES6实现
  2. 继承实现
  3. 案例练习

ES6实现

  • 生成实例对象的传统方式
  • ES6实现方式

ES6实现

  • 生成实例对象的传统方式
//生成实例对象的传统方式
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实现

  • ES6实现方式
//ES6实现方式
//定义类
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

通过构造函数和原型-创建对象

  • 构造函数的prototype属性,在 ES6 的“类”上面继续存在。
  • 类的所有方法都定义在类的prototype属性上面。
class Point {
  constructor() {
    // ...
  }

  toString() {
    // ...
  }

  toValue() {
    // ...
  }
}

// 等同于
Point.prototype = {
  constructor() {},
  toString() {},
  toValue() {},
};

ES6实现

  • constructor 方法
    • 类的默认方法
    • 通过new命令生成对象实例时,自动调用该方法
    • 一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
class Point {
}

// 等同于
class Point {
  constructor() {}
}

Class 的静态方法

  • 使用static关键字定义静态方法
  • 静态方法包含this关键字,这个this指的是类,而不是实例。
class Foo {
  static classMethod() {
    return 'hello';
  }
}

Foo.classMethod() // 'hello'

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

Class 的静态属性和实例属性

  • 静态属性
    • Class 本身的属性,即Class.propName,而不是定义在实例对象(this)上的属性。
//静态属性
class Foo {
}
Foo.prop = 1;
Foo.prop // 1

//实例属性
//类的实例属性可以用等式,写入类的定义之中。
class MyClass {
  myProp = 42;

  constructor() {
    console.log(this.myProp); // 42
  }
}

继承实现

  • 利用extends关键字实现
  • 子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
class Point {
}

class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y); // 调用父类的constructor(x, y)
    this.color = color;
  }

  toString() {
    return this.color + ' ' + super.toString(); // 调用父类的toString()
  }
}

babel

  • 用于编写下一代javascript的编译器
  • 即刻使用ES6语法
    • 使用在线支持
    • 本地编译
<!-- 加载 Babel -->
<script src="https://cdn.bootcss.com/babel-standalone/6.26.0/babel.min.js"></script>
<!-- 你的脚本代码 -->
<script type="text/babel">
const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();
</script>

案例练习

案例练习

交互开发

旨为前端开发工程师的前端开发课程