上一篇整理了es6解構語法相關的一塊知識(【ES6系列】解構賦值(整理篇))。這一篇,要整理的是class相關的知識。es6
class就是類,和ES5中的構造函數十分類似,絕大部分功能都是一致的,可是class的寫法,能讓對象原型的功能更加清晰,更加符合面嚮對象語言的特色。函數
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.sayPoint = function() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
複製代碼
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
sayPoint() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
}
複製代碼
一、constructor就是原來構造函數的寫法。 二、定義類的方法的時候,並不須要加逗號,也不須要加function post
class的內部全部定義的方法,都是不可枚舉的。而原型上面定義的方法都是能夠枚舉的。ui
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
sayPoint() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
}
Object.keys(Point.prototype); //[]
複製代碼
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.sayPoint = function() {
console.log(`x: ${this.x}, y: ${this.y}`);
}
Object.keys(Point.prototype); //['sayPoint']
複製代碼
constructor
是類的默認方法,就算不定義,也會有一個空的constructor
。this
class Point {
}
// 等同於
class Point {
constructor() {
}
}
複製代碼
class Point {
constructor() {
return Object.create(null);
}
}
new Point() instanceof Point
// false
複製代碼
class Point {
constructor() {
return Object.create(null);
}
}
Point();
// Class constructor Point cannot be invoked without 'new'
複製代碼
getter和setter就是攔截器,在作某個操做的時候,能夠添加一些自定義的東西。spa
class Point{
constructor() {
// ...
}
get x() {
console.log('getter');
}
set x(val) {
console.log(`setter: ${val}`)
}
}
const p = new Point();
p.x = 1;
// setter: 1
p.x
// getter
複製代碼
class內部默認就是嚴格模式。prototype
new Point(); // SyntaxError: Identifier 'Point' has already been declared
class Point{}
複製代碼
類是對ES5構造函數的一層封裝,因此不少屬性都被class繼承,包括name這個屬性。code
class Point{}
Point.name // Point
複製代碼
正常狀況下,this的指向都是類的實例。可是當你單獨把其中的方法拿出來調用,那麼就會發生報錯。對象
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
print() {
console.log(this);
console.log(`x: ${this.x},y: ${this.y}`);
}
}
const p = new Point();
let {print} = p;
print();
複製代碼
上述例子中,輸出的this是undefined。由於this會指向當前函數運行的環境之下,可是class內部定義了嚴格模式,因此this爲undefined。繼承
靜態方法是指class上的方法不會被實例繼承。關鍵詞——static
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static print() {
console.log(this);
console.log(`x: ${this.x},y: ${this.y}`);
}
}
const p = new Point();
p.print(); // p.print is not a function
Point.print(); // x: undefined,y: undefined
複製代碼
靜態屬性並無static這個關鍵詞。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static print() {
console.log(this);
console.log(`x: ${this.x},y: ${this.y}`);
}
}
Point.z = 1;
const p = new Point();
p.z //undefined
複製代碼
當一個屬性值並無在初始化的時候賦值,咱們能夠像下面那麼寫:
class Point{
constructor() {
this.x = 1;
this.y = 2;
}
}
// 等同於
class Point{
x = 1;
y = 2;
}
複製代碼
這一篇整理了class的一些基礎語法。下一篇將會整理class的繼承相關。