Assignment in constructor, access modifier of member variables


#1

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?


#2

Disclaimer: I speak in no official capacity about anything. I just have been at this a long time.

I completely agree with you about everything. The fact that TypeScript desugars constructor parameters with access modifiers into variable declarations and assignments is underdocumented, but I think it should be encouraged.

IMHO, JavaScript is a horrible language. It doesn’t actually enforce access control, so public and private aren’t nearly as useful as they are in other languages. Your instinct to make things private by default is good; a common JavaScript idiom is to prefix such private members with an underscore. TypeScript will do its best to enforce access control, but it is limited by the underlying faults of JavaScript.

However, I don’t agree with people who want to make absolutely all instance variables private and only allow access via getter and setter methods, if those methods do nothing but get and set. If they do other things (like manage cache consistency), fine. If they add nothing else to the party, I don’t see any benefit provided over a public instance variable.


#3

This is something that I’ve been meaning to update…and have let slipped a bit :smile:

I will clean this up through out the upcoming weeks.