實用類的注意事項
三個注意點:
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/79808.html
標籤:JavaScript
