在學習ES6 class類之前,先看下傳統生成實例對象的方法(構造函數)。
function Person(name, age){
this.name = name;
this.age = age;
this.intr = function(){
console.log(name + ' is ' + age + ' years old');
}
}
var p = new Person('jack', 20);
p.intr();//jack is 20 years old
上面這種寫法與面向對象差異很大,在ES6中,引入了class(類)這個概念,讓對象原型的寫法更加清晰、更像面向對象編程的語法。
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
intr(){
console.log(this.name + ' is ' + this.age + ' years old');
}
}
var p = new Person('jack', 20);
p.intr();
在用法上,與ES5的構造函數基本一致,也是使用new關鍵字創建實例對象。
類的所有方法都定義在類的prototype屬性上面
class Person{
constructor(){
// ...
}
intr(){
//...
}
}
// 等同於
Person.prototype = {
constructor(){},
intr(){}
};
在類的實例上面調用方法,其實就是調用原型上的方法。
類的內部,默認就是嚴格模式,所以不需要使用use strict指定運行模式。
類不存在變量提升,這一點與 ES5 完全不同。
靜態屬性
靜態屬性指的是 class 本身的屬性,即class.propName,而不是定義在實例對象(this)上的屬性。
class xiangqi{
constructor(name){
this.name = name;
}
static width = 50;
static height = 50;
intr(){
console.log(this.name + '的大小' + xiangqi.width + ',' + xiangqi.height);
}
}
var horse = new xiangqi('馬');
horse.intr();//馬的大小50,50
寫法是在實例屬性的前面,加上static關鍵字。
靜態方法
如果在一個方法前,加上static關鍵字,就表示該方法不會被實例繼承,而是直接通過類來調用,這就稱爲“靜態方法”。
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
static intr(){
console.log(this.name + ' is ' + this.age + ' years old');
}
}
Person.intr();//Person is undefined years old
var p = new Person('jack', 20);
p.intr();//報錯
Person類的intr方法前有static關鍵字,表示該方法是靜態方法,可以在Person類上調用。如果在Person類的實例上調用,就會報錯,表示沒有該方法。