🚀Classes and Interfaces
Classes and interfaces (OOP)
Last updated
Classes and interfaces (OOP)
Last updated
We have name attribute. We can also add some methods (functions) to this Department class.
So one way we can solve this is by using name inside newAccounting like this to solve 'this' keyword
So the idea is, caller variable (or object whose is calling the method) should take care that the 'this' keyword is implemented properly. It's responsibility of caller to check if that prop (eg. name) exists which is required by the method. To avoid that compilation error, we have added the this parameter and we have set it's type to Department class, saying that, whatever attributes department class has, make sure you provide that in caller so that this
inside the describe method won't fail.
Let's say we define employees array in Department class
and we have a method to add employees from within the class
Let's add method to add employees and also to print them
Now, to add and print employees we can call these methods on instance
One problem we have here is that, we can add employees by not calling addEmployee()
inside the class on instance methods. For example, we could do
When building this, we should better avoid multiple ways of adding an employee and do it one single way to avoid confusion. May be there is a validation that happens when we call addEmployee() before it actually adds an employee and we might not get those validations on directly adding it to array.
So to avoid adding employee from outside, we can make employees variable private so that this cannot be accessed like this instance.employees[2] = 'anna'
Similar to access modifiers private and public we learnt above. Let's say we have a field that's not only private but also should not be changed once assigned inside the class. For example, id shouldn't change after initialization, for this we can use readonly modifier.
Just like private and public, readonly is only understood by TS and doesn't exist in JS.