0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【JavaScript】ES5とES6において、親クラス継承の違い

Posted at

##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などの構造と似ているように思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?