JavaScript的寫類方式(6)

時間到了2015年6月18日,ES6正式發佈了,到了ES6,前面的各類模擬類寫法均可以丟掉了,它帶來了關鍵字 class,extends,super。javascript

 

ES6的寫類方式html

// 定義類 Person
class Person {

  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  setName(name) {
    this.name = name;
  }

  getName() {
    return this.name;
  }

  toString() {
    return 'name: ' + this.name + ', age: ' + this.age;
  }

}

// 建立實例對象
var p = new Person('Backus', 35);
p instanceof Person; // true

以上定義了一個類,constructor 是構造器,這點和 Java 不一樣,Java的構造器名和類名相同。java

 

和 Java 多象啊,再看看繼承post

class Man extends Person {
  constructor(name, age, school) {
    super(name, age); // 調用父類構造器
    this.school = school;
  }

  setSchool(school) {
    this.school = school;
  }

  getSchool() {
    return this.school;
  }

  toString() {
    return super.toString() + ', school:' + this.school; // 調用父類的toString()
  }
}

var man = new Man('張三', '30', '光明中學');
man instanceof Man; // true
man instanceof Person; // true
console.log(man);

以上代碼中,constructor 和 toString 方法中,都出現了 super 關鍵字,它指代父類的實例(即父類的 this 對象)。 以前 ES5 有個 Object.getPrototypeOf 來獲取父類的原型對象this

 

 

能夠繼續閱讀:spa

JavaScript繼承方式(1)

相關文章
相關標籤/搜索