ECMAScript 6面向对象

2017-07-24  本文已影响5人  竹小星

ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。

定义类:

class Parent{                     
  constructor(name,age){            // 类里自带的构造方法
    this.name = name;               // this是实例对象
    this.age = age;                 // 设置属性
  }
  play(){                           // 设置方法
    alert('我叫'+this.name);
  }
}

ES6 的类相当于构造函数的另一种写法

class Parent{
  // ...
}
typeof Parent           // "function"

类的数据类型是函数,也就是指向构造函数。

继承:

Class 可以通过extends关键字实现继承

class Child extends Parent{
  constructor(name,age){            
    super(name,age);        // 继承父级的属性, 
    this.sex = sex;         // 子类没有自己的this对象,而是继承父类的this对象,进行加工
  }
  showSex({
    alert('我是'+this.sex+'的')
  })
}
上一篇 下一篇

猜你喜欢

热点阅读