##ES5においての継承
<script>
//親
function Phone(brand, price) {
this.brand = brand;
this.price = price;
}
Phone.prototype.call = function () {
console.log(" give XXX a call")
}
//子
function smartPhone(brand, price, color, size) {
Phone.call(this, brand, price);
this.color = color;
this.size = size;
}
smartPhone.prototype = new Phone; //親を呼び出す
smartPhone.prototype.constructor = smartPhone;
//子 メソッドの追加
smartPhone.prototype.photo = function () {
console.log("take photo")
}
smartPhone.prototype.mail = function () {
console.log("receive email")
}
let iphone = new smartPhone('iphone', 100, 'white', '6.7inch');
console.log(iphone);
//smartPhone{brand: 'iphone', price: 100, color: 'black',size: '6.7inch'}
</script>
##ES6での継承
<script>
//親
class Phone {
constructor(brand, price) {
this.brand = brand;
this.price = price;
}
call() {
console.log(" give XXX a call")
}
}
//子 *** extendsを使えば継承できる ***
class smartPhone extends Phone {
constructor(brand, price, color, size) {
supre(brand, price); //イコール Phone.call(this,brand,price)
this.color = color;
this.size = size;
}
photo() {
console.log("take photo")
}
mail() {
console.log("receive email")
}
}
let iphone = new smartPhone('iphone13', 200, 'pink', '6.1inch')
console.log(iphone)
//smartPhone{brand: 'iphone13', price: 200, color: 'pink',size: '6.1inch'}
iphone.call()//" give XXX a call"
iphone.photo() //"take photo"
iphone.mail() //"receive email"
</script>
##違い
ES6とES5と比べて、親クラスを継承するときのコードが明らかに簡潔ですね。
classとextendsを使えば、親クラスを継承できるので、
PHP、Javaなどの構造と似ているように思います。