戻る

クラスメソッド
public / private / static

クラスメソッドとは、クラスを介して使用可能なメソッドです。

[パブリックメソッド]
クラス外部からもアクセス可能なメソッドです。

[プライベートメソッド]
#(ハッシュ)をメソッド名の前に付けます。
クラス外部からはアクセスできません。

[スターティックメソッド]
インスタンス化しないで参照可能なメソッドです。

[サンプル]
copy
class A{
	constructor(num1)
	{
		this.num1 = num1;
	}
	test1(num2)
	{
		return this.#test2(this.num1 + num2);
	}
	#test2(num)
	{
		if(num > 5)
		{
			num++;
		}
		else
		{
			num * 2;
		}
		return num;
	}
	#test3(num)
	{
		console.log(this.#test2(num));
	}
}
const cls1 = new A(5);
console.log(cls1.test1(1));//7

//Uncaught TypeError: cls1.test2 is not a function
//console.log(cls1.test2(2));

//Uncaught TypeError: cls1.test3 is not a function
//console.log(cls1.test3(6));
インスタンス化したクラスをオブジェクトからメソッドを実行したサンプルです。

console.log(cls1.test1(1));//7
下記のステップが実行されます。

return this.#test2(this.num1 + num2);
this.num1 : 5(constructorの引数をpublicフィールドに保存した値)
num2 : 1(引数)
5 + 1 = 6の結果を引数として、privateメソッド(#test2)を実行します。

#test2(num)
条件によって分岐した結果を返します。

console.log(cls1.test2(2));
test2はprivateメソッドなので実行できません。

console.log(cls1.test3(6));
test3はprivateメソッドなので実行できません。


[サンプル]
copy
class B{
	static num1 = 2;
	static #num2 = 3;
	static test1 (num)
	{
		return this.#test3(num);
	}
	static #test2 (num)
	{
		return this.#test3(num);
	}
	static #test3(num)
	{
		return (this.num1 + this.#num2 + num) * 2;
	}
}
console.log(B.test1(4));//18
//Uncaught TypeError: B.test2 is not a function
//console.log(B.test2(4));
static関数を使用する場合、クラス内部からメソッドを実行する場合はstaticである必要があります。

console.log(B.test1(4));//18
staticメソッドを実行しているため、クラスBをインスタンス化しなくても
そのまま使用できます。
内部ではstaticのprivateメソッドをコールした結果を返しています。

console.log(B.test2(4));
staticですがprivateであるため、クラスBから実行はできないため
Uncaught TypeError: B.test2 is not a function
というエラーが返ります。


戻る


著作権情報
ホームページおよプリ等に掲載されている情報等については、いかなる保障もいたしません。
ホームページおよびアプリ等を通じて入手したいかなる情報も複製、販売、出版または使用させたり、
または公開したりすることはできません。
当方は、ホームペーよびアプリ利用したいかなる理由によっての障害等が発生しても、
その結果ホームページおよびアプリ等を利用された本人または他の第三者が被った損害について
一切の責任を負わないものとします。