時間到了2015年6月18日,ES6正式發布了,到了ES6,前面的各種模擬類寫法都可以丟掉了,它帶來了關鍵字 class,extends,super。
ES6的寫類方式
// 定義類 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 多象啊,再看看繼承
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 來獲取父類的原型對象。
可以繼續閱讀:
