- 繼承:子類可以繼承父類的一些屬性和方法
<body>
<button>加法 </button>
<script>
var that;
class Father{//父類
constructor(x,y){
that = this;
this.x=x;
this.y=y;
this.btn=document.querySelector('button');
this.btn.onclick=this.sum;
}
sum(){
//這里的this 指向btn,因?yàn)閎tn調(diào)用了這個(gè)方法,
console.log(that.x+that.y);//that存的是構(gòu)造函數(shù)里的this
}
say(){
console.log("Father");
}
}
class Son extends Father{//子 繼承父
constructor(x,y){
super(x,y);//調(diào)用父類的構(gòu)造函數(shù),super必須放在子類this之前
this.x=x;
this.y=y;
}
say(){
console.log("Son");
console.log(super.say())
}
}
var son = new Son(2,6);
son.sum();
var sonTwo = new Son();
sonTwo.say();
</script>
<body>
子類調(diào)用父類的函數(shù)要用到super關(guān)鍵字,可以調(diào)用構(gòu)造函數(shù)也可以調(diào)用普通函數(shù)。this的指向是誰調(diào)用指向誰。子類的構(gòu)造函數(shù)中的this指向的是子類。
繼承中如果實(shí)例化子類并輸出一個(gè)方法,先看子類有沒有,然后再看父類,如果子類有就先執(zhí)行子類,子類沒有才執(zhí)行父類的方法(就近原則)
super關(guān)鍵字在子類中,必須放到子類this關(guān)鍵字之前
ES6 中是沒有變量提升的,必須先定義類,才能實(shí)例化對(duì)象。類里邊的共有的屬性和方法要用this關(guān)鍵字使用
constructor 里面的this指向的是創(chuàng)建的實(shí)例對(duì)象,方法里的this指向方法的調(diào)用者