粗看ES6之面向對象寫法

標籤: es6html


在es6之前,js沒有類的概念,雖然有構造函數原型的方式用來作面向對向開發,可是對於書法並非十分友好,並且對於繼承實現也不是十分友好。
es6引入class constructor extends super等關鍵字簡化了JS面向對象寫法,之後能夠跟後端說JS也終因而有類的一門語言了,哈哈。
ES6的面向對象寫法以下:es6

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>es6面向對象寫法</title>
</head>
<body>
    <script>
        //js類寫法
        class Test{
          constructor(a,b){
            this.attr0 = a;
            this.attr1 = b;
          }
          fn(){
            console.log(this.attr0,this.attr1)
          }
        }
        //初始化方法和之前構造函數原型方式同樣,都是經過new關鍵字
        var testFn = new Test(1,2);
        testFn.fn();
    </script>
</body>
</html>

在線測試編程


es6經過extends super實現繼承
示例代碼以下:後端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>es6面向對象繼承寫法</title>
</head>
<body>
    <script>
        //js類寫法,Test類
        class Parent{
          constructor(a,b){
            this.attr0 = a;
            this.attr1 = b;
          }
          fn(){
            console.log(this.attr0,this.attr1);
          }
        }

        //寫一個繼承自Parent的類
        class Child extends Parent{
            constructor(a,b,c){
              super(a,b);//實現繼承parent上的方法&屬性
              this.attr2 = c;
            }
            fn0(){
              console.log(this.attr2);
            }
        }

        //初始化方法和之前構造函數原型方式同樣,都是經過new關鍵字
        var testFn = new Child(1,2,3);
        testFn.fn();
        testFn.fn0();
    </script>
</body>
</html>

在線測試函數

我的以爲自此jser真的能夠愉快的進行面向對象編程了,666666,同時祝all新年快樂!!測試

相關文章
相關標籤/搜索