Class内でしか参照できない変数や関数をプライベート変数・関数(private var func)と呼びます。
プライベートな関数・変数は、Classをインスタンス化したあとに外部から変更・参照されないため、安全にプログラムを書くために必須の機能です。
今回は、Classが使えない環境でよく使われるjsのコンストラクタ関数でプライベートな関数や変数を定義する方法をご紹介いたします。
コンストラクタ関数でプライベートな変数・関数を使う
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
function Car() { let defaultColor = 'red'; let changeLocation = (distance) => { this.location += distance; } this.color = defaultColor; this.location = 0 this.drive = () => { changeLocation(10); } this.speedDrive = () => { changeLocation(30); } } const constructorCar = new Car(); console.log(constructorCar.defaultColor); // undefined console.log(constructorCar.color); // red console.log(constructorCar.location); // 0 try { constructorCar.changeLocation(10); } catch(e) { console.log('error'); } console.log(constructorCar.location); // 0 constructorCar.drive(); console.log(constructorCar.location); // 10 constructorCar.speedDrive(); console.log(constructorCar.location); // 40 |
こちらのソースのように、コンストラクタ関数でprivateな変数や関数を宣言したい場合、【this】を使わずに、関数内でletやconstを使うことで実現が可能です。
this.colorやthis.locationといった、this(ここではCarを指す)に生やした変数は、インスタンス化した後に外部から参照・変更が可能ですが、letで宣言されたprivateな関数や変数は外部から参照・変更が不可能です。
コンストラクタ関数内でしか使用しない変数や関数は、let・constで宣言し、インスタンス化された後に参照できないようにすることで、安全にプログラムを拡張していくことが可能になります!