天天看點

ES6的constructor() 函數

ES6引入了class類的概念,建立的每一個class類,都會有一個constructor()方法,該方法是一種用于建立和初始化class建立的對象的特殊方法--構造函數方法。

eg:    

class Animal {
    constructor() {
        this.name = "animal";
    }
}

let animal = new Animal();
console.log(animal.name);

//輸出:animal,是以 Animal類裡的constructor()方法裡的 this 指向的是被建立的執行個體對象
           

如果一個類沒有指定constructor() 方法,則會添加預設的constructor()方法;

class Animal(){}
等同于
class Animal(){
    constructor(){}  //預設的constructor方法
}
           

一個類隻允許有一個constructor()方法,如果出現多個,則會報:Uncaught SyntaxError: A class may only have one constructor

類的繼承:

子類繼承父類,會同時繼承父類的私有屬性方法,constructor()為私有屬性方法

class Animal {
  constructor() { 
    this.name = "animal";
    this.age = "20";
  }
}
// Dog 繼承 Animal 
class Dog extends Animal {
  constructor() {
    super(); //使用extend必須使用super(); super關鍵字來調用父類的構造方法;
    this.name = "dog";
  }
}
let animal = new Animal();
console.log(animal.name + '-' + animal.age);
//輸出:animal-20  
let dog = new Dog();
console.log(dog.name + '-' + dog.age);
//輸出:dog-20  age繼承父類的 age:20
           

如果使用Object.setPrototypeOf方法改變被繼承的類的原型,構造函數(constructor)不會被改變繼承,因為Object.setPrototypeOf方法是針對對象執行個體的,而不是構造函數(類):

class Food { }
Object.setPrototypeOf(Dog.prototype, Food.prototype);

console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); //false
console.log(Object.getPrototypeOf(Dog.prototype) === Food.prototype); //true

let dog = new Dog();
console.log(dog.age);
//輸出:20 ,Dog的原型被改變,但是仍然調用的是Animal的構造函數
           

如有錯誤,請指出,多多指教。