On pages in the Docs for ionic 2 it shows code like
constructor(nav: NavController) {
this.nav = nav;
}
(for example here: http://ionicframework.com/docs/v2/api/components/modal/Modal/)
Now is understand what it does: The formal parameter uses dependency injection and within the constructor the passed nav
of type NavController
is assigned to the member variable this.nav
when the constructor is called.
My question is: is that assignment this.nav = nav
really necessary? Or what is it good for? Is this just a habit in JavaScript development?
I have built several apps with ionic 2 for practice where I wrote
constructor(private nav: NavController) {
// empty constructor body
}
and it worked perfectly fine for my little demo apps. However, I’m not too sure whether I might run into problems when the app gets more complex, especially when you consider objects being injected other than nav
or navparams
.
And, adding to the example above, my second question:
In the soruce code of many tutorial and demos I’ve seen that they often use either public
or no access modifier at all.
I’m wondering which one is “better”. Or put differently: what’s good or bad about public
or private
in an ionic 2 app?
From programming courses at college I’ve learned that in OOP you try to set as many variables private
as possible (and access them through getter/setter methods where you have control over what’s happening to member variables) and only public
if there is a good reason for it. What is the reason in ionic 2 to set member variables public
?