ES6中對class的理解(一)

自己的理解,有錯誤還望指出:

        在學習JavaScript的時候,我們知道他是沒有類(class)的寫法的,所以我們需要類的時候一般是使用構造函數來模擬類的寫法。在ES6中提供了class寫法,在ES5中是沒有的,有時候我們在寫一個構造函數的時候,使用的是function來寫一個構造函數,但是這種函數式編程的方式,很難直觀的發現構造函數。如下:

       在ES5中,我們寫一個構造函數(模擬類)的時候會這麼寫,可以看到這個也是一個函數,但是我將名字的第一位大寫,這樣可以區分於普通函數。。。並且通過this.x來將屬性或者方法綁定在該構造函數裏面去。

ES5寫類

function Cus(a,b){
    this.a = a;
    this.b = b;
    this.add = function (){
        return this.a +this.b
    }
}
var c = new Cus()
console.log(c.add())

假設我們現在使用的是ES6來寫一個類,儘管提供了一個class的寫法,但是下面這種寫法是錯的,如下:

class CUS{
    this.a = 12;
    this.b = 13;
    this.add = function (){
        return this.a +this.b
    }
}

爲什麼不能使用this,那是因爲這裏的類都沒有實例化,也就是說我們還沒有創建一個類的實例,this是要綁定到對象上面去的,這裏就要講到ES6 的構造器constructor()

ES6寫類

class Person {
    constructor() {
        this.firstname = "Ymw";
        this.lastname = "ming";
        this.add = function(){
            return this.firstname+' '+this.lastname
        }
    }
}

var person1 = new Person();

console.log(person1.firstname+' '+person1.lastname); //Ymw ming
console.log(person1.add()); //Ymw ming

這裏我把add方法也放在了構造器裏面,雖然可以這麼做,但是建議constructor()裏面只放屬性,方法寫在constructor()平行位置的下邊,如:

class Person {
    constructor() {
        this.firstname = "Ymw";
        this.lastname = "ming";
        this.add = function(){
            return this.firstname+' '+this.lastname
        }
    }
    say() {
        return "hi,"+this.firstname+' '+this.lastname
    }
}

var person1 = new Person();

console.log(person1.firstname+' '+person1.lastname);//Ymw ming
console.log(person1.add());  //Ymw ming
console.log(person1.say());  //hi,Ymw ming

class傳參數

千萬不要在class旁邊寫個括號傳參數,這個是錯的,一般編輯器就會提示出錯了,正確的寫法是寫在constructor()括號內,如下:

class Person {
    constructor(first,last) {
        this.firstname = first;
        this.lastname = last;
        this.add = function(){
            return this.firstname+' '+this.lastname
        }
    }
    say() {
        return "hi,"+this.firstname+' '+this.lastname
    }
}

var person1 = new Person('Ymw',"ming");

console.log(person1.firstname+' '+person1.lastname);//Ymw ming
console.log(person1.add());  //Ymw ming
console.log(person1.say());  //hi,Ymw ming

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章