LoginSignup
1
0

More than 3 years have passed since last update.

JavaScript復習③

Last updated at Posted at 2021-01-27

JavaScript復習②からの続きです。

様々な戻り値

JavaScriptファイル

const check = (number)=> {
  return number % 2 === 0;
};
console.log(check(6));
console.log(check(7));
コンソール
true
false

オブジェクトと関数

JavaScriptファイル
const user = {
  name: "たろう"
  greet: ()=> {
    console.log("こんにちは!");
  }
};
user.greet(); //関数の呼び出し
コンソール
こんにちは!

インスタンス

JavaScriptファイル
class Animal {
}
const animal = new Animal();
console.log(animal);
コンソール
Animal{ } //空のオブジェクト

コンストラクタ

JavaScriptファイル
class Animal {
  constructor() {
    console.log("こんにちは!");
  }
}
const animal1 = new Animal();
const animal2 = new Animal();
コンソール
こんにちは!
こんにちは!

インスタンスとプロパティ

JavaScriptファイル
class Animal {
  constructor() {
    this.name = "タロウ";
  }
}
const animal = new Animal();
console.log(animal.name);
コンソール
タロウ

コンストラクタの引数

JavaScriptファイル
class Animal {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
const.animal = new Animal("タロウ", 20);

メソッド

JavaScriptファイル
class Animal {]
  constructor(name, age) {
       .
       .
  }
  info() {
    console.log(`名前は${this.name}です`);
  }
}
const animal = new Animal("タロウ", 20);
animal.info();
コンソール
名前はタロウです

メソッド内でメソッドを使う

JavaScriptファイル
class Animal {
  greet() {
    console.log("こんにちは");
  }
  info() {
    this.greet();  //同じクラスのメソッドを実行
        .
        .
  }
}

継承

JavaScriptファイル
// Animalクラスを継承
class Dog extends Animal {
}

メソッドの戻り値

JavaScriptファイル
class Dog extends Animal {
  getHumanAge() {
    return this.age * 7;
  }
}
const dog = new Dog("タロウ", 20);
const humanAge = dog.getHumanAge();
console.log(humanAge);
コンソール
140

子クラスのメソッド

子クラスで定義した独自のメソッドは親クラスから呼び出すことはできない

オーバーライド

親クラスと同じ名前のメソッドを子クラスに定義すると、子クラスのメソッドが優先して使用される。
(子クラスのメソッドが親クラスのメソッドを上書きしている)
→オーバーライドという

続きはJavaScript復習④
1
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
1
0