實用類的注意事項函數
三個注意點:this
1.在ES中類沒有變量的提高,因此必須先定義類,才能經過實例化對象spa
2.類裏面的共有屬性和方法必定要加this使用code
3.類裏面的this使用問題:對象
4.constructor裏面的this指向實例化對象,方法裏面的this指向這個方法的調用者blog
<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>