ES6問答-class繼承

class的繼承:

前置內容javascript

class Point {
     constructor(x, y) {
      this.x = x
      this.y = y
     }
     toString() {
        return `(${this.x},${this.y})`
     }
     /* 靜態方法 */
     static hello() {
        console.log("hello world!")
     }
    }

    // 子類實例的構建,基於父類實例
    // super 方法調用父類的實例。使用了super後,才能用this
    class ColorPoint extends Point {
     constructor(x, y, color) {
      super(x, y) // super做爲方法,用在子類的構造,必須在this以前先調用
      this.color = color
     }
     toString() {
      //  super做爲對象(對象調用方法),指向的是父類的原型對象即Point.prototype
      console.log(Point.prototype.toString === super.toString) // true
      return `color: ${this.color}, ${super.toString()}`
     }
    }
  1. 子類和父類是經過什麼關鍵字實現繼承?父類是Point,子類是ColorPoint如何寫?java

    經過extends關鍵字函數

    class ColorPoint extends Point{
     
    }
  2. 子類的屬性和方法中,哪一個關鍵字是必須的?這個關鍵字怎麼用?爲何要這麼用?this

    super關鍵字必須。prototype

    super關鍵字有兩種用法,做爲方法和做爲對象。code

    做爲方法時,用在constructor方法中(用於子類的構造),必須在this以前調用。對象

    做爲對象時,用在其餘方法中,調用父類的方法用。指向的是父類的原型對象。繼承

    Point.prototype.toString === super.toString // true
    /*
    super做爲對象時,不能不調用方法,直接拿來用,好比  Point.prototype === super 就會控制檯報錯
    */
  3. ColorPoint.hello()會輸出什麼?爲何?

    會輸出 hello world! 由於ColorPointPoint的子類,會繼承它的全部方法。hello()Point的靜態方法,也會被子類ColorPoint繼承。ip

  4. 如何從子類獲取父類?代碼演示get

    Object.getPrototypeOf(ColorPoint) === Point   //true

    Object.getPrototypeOf(childClass) 的方法能夠判斷一個類是否繼承了另外一個類

  5. 簡述一下super的兩種使用場景

    super可做爲方法,也可做爲 對象

    方法:子類的constructor中使用。

    對象:在子類的其餘方法中使用。普通方法 = > 指向父類原型對象(父類的方法所有定義在原型對象上); 靜態方法 => 指向父類

  6. 子類的__proto__屬性,指向的是什麼?

    子類的__proto__屬性指向父類

    colorPoint.__proto__ === Point // true
    // 構造函數的繼承
  7. 子類的prototype屬性的__proto__屬性指向什麼?

    子類的prototype屬性的__proto__屬性指向父類的prototype屬性

    colorPoint.prototype.__proto__ === Point.prototype  // true
    // 類的方法的繼承
  8. 原生構造函數有哪些?簡述下Boolean構造函數的用法.
    Boolean Number String Array Date Function Regexp Error Object

    Boolean()  
    Boolean 對象是一個布爾值的對象包裝器。當須要判斷一個對象是正負時,能夠這麼作
    將非布爾值轉化爲布爾值,用Boolean方法,Boolean(exp) 或者 !!(exp)
  9. ES5的方法實現繼承,能夠繼承到原生的構造函數嗎?爲何?

    ES5是先新建子類的實例對象this,再將父類的屬性添加到子類上。因爲父類的內部屬性沒法獲取,致使沒法繼承原生的構造 函數。

  10. ES6的方法實現繼承,能夠繼承到原生的構造函數嗎?爲何?

    ES6 是先新建父類的實例對象this,而後再用子類的構造函數修飾 this,使得父類的全部行爲均可以繼承。

相關文章
相關標籤/搜索