ES6 中的Class

基本用法

ES5 的寫法函數

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};

var p = new Point(1, 2);

ES6 的寫法this

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

在類的實例上面調用方法,其實就是調用原型上的方法。spa

class B {}
let b = new B();

b.__proto__.constructor === B.prototype.constructor?console.log("true"):console.log("false")
console.log(typeof b.__proto__.constructor)
console.log(typeof B.prototype.constructor)

clipboard.png

注:類的內部全部定義的方法,都是不可枚舉的 prototype

constructor 方法

constructor方法是類的默認方法,經過new命令生成對象實例時,自動調用該方法。一個類必須有constructor方法,若是沒有顯式定義,一個空的constructor方法會被默認添加。
注意點3d

  • constructor方法默認返回實例對象(即this),徹底能夠指定返回另一個對象。code

    class Foo {
      constructor() {
        return Object.create(null);
      }
    }
    
    new Foo() instanceof Foo
    // false
  • 類必須使用new調用,不然會報錯。對象

    class book{
        constructor(){
            this._year=2004;
            this.edition=1;
        }
        get year(){
            return this._year;
        }
        set year(newVal){
            if(newVal>2004){
                this._year=newVal;
                this.edition+=newVal-2004;
            }
        }
    }
    let b=new book();
    b.year = 2004; //2
    console.log(b.edition);

取值函數(getter)和存值函數(setter)

class book{
    constructor(){
        this._year=2004;
        this.edition=1;
    }
    get year(){
        return this._year;
    }
    set year(newVal){
        if(newVal>2004){
            this._year=newVal;
            this.edition+=newVal-2004;
        }
    }
}
let b=new book();
b.year = 2004; //2
console.log(b.edition);

clipboard.png

相關文章
相關標籤/搜索