我們說一下ES6中類和對象的注意問題

實用類的注意事項

三個注意點:

1.在ES中類沒有變量的提升,所以必須先定義類,才能通過實例化對象

2.類裏面的共有屬性和方法一定要加this使用

3.類裏面的this使用問題:

4.constructor裏面的this指向實例化對象,方法裏面的this指向這個方法的調用者

 

<script>
        var that;
        var _that;
        class Star {
            // constructor 裏面的this 指向的是 lbw
            constructor(uname , age) {
                that =  this;

                console.log(this);
                
                this.uname = uname;
                this.age = age;
                this.dance();
                //this.sing();
                this.btn = document.querySelector('button');
                this.btn.onclick = this.sing;
            }
            sing() {
                //這個sing方法裏面的this 指向的是 btn這個按鈕 因爲這個按鈕調用了這個函數
                console.log(that.uname);
            }
            dance() {
                _that = this;//這個dance裏面的this 指向的是實例對象ldh因爲ldh調用了這個函數
                console.log(this);
                
            }
        }
        var lbw = new Star('劉德華');
        console.log(lbw ===that);//
        console.log(lbw ===_that);
        
        //1.在ES6類沒有變量提升,所以必須先定義類,才能通過類實例化對象
        //2.類裏面的共有的 屬性和方法 一定要加到this裏使用。
    </script>

 

 

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