「React」クラスにメソッドを定義するサンプル
書式
Class クラス名 {
メソッド名() {
return xxx
}
}
Class クラス名 {
メソッド名() {
return xxx
}
}
Class クラス名 { メソッド名() { return xxx } }
使用例
<!DOCTYPE html>
<html>
<body>
<script>
/*クラスの定義*/
class Car {
constructor(name,addr) {
this.brand = name;
this.addr = addr
}
/*メソッドの定義*/
info() {
return 'メーカー: ' + this.brand + " 産地:" + this.addr ;
}
}
cftcar = new Car("日産","東京");
document.write(cftcar.info());
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<script>
/*クラスの定義*/
class Car {
constructor(name,addr) {
this.brand = name;
this.addr = addr
}
/*メソッドの定義*/
info() {
return 'メーカー: ' + this.brand + " 産地:" + this.addr ;
}
}
cftcar = new Car("日産","東京");
document.write(cftcar.info());
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <script> /*クラスの定義*/ class Car { constructor(name,addr) { this.brand = name; this.addr = addr } /*メソッドの定義*/ info() { return 'メーカー: ' + this.brand + " 産地:" + this.addr ; } } cftcar = new Car("日産","東京"); document.write(cftcar.info()); </script> </body> </html>
結果
メーカー: 日産 産地:東京