I have this Try it Yourself TypeScript Parameter Properties example from W3Schools in the screenshot below.
I am a bit confused as to why the name Jane gets displayed to the screen when there is this code.
My understanding is that the code below assigns a a variable to a class Person
const person = new Person ("Jane")
console.log code calls a getName() function with this code
console.log(person.getName())
Inside class Person, a public visibility modifier has a function that returns a name with
public getName(): string {
return this.name;
}
But how can it get the name when this code has a private member variable inside a public constructor
public constructor(private name: string) {}
I though that a private member only allows access to a class member (in this case name) from within the class
How does it work when you have a private member within a public constructor like this ?
If someone can give me a good understanding on why it can still work like this, then that will be appreciated help, thanks ?
Note:- Constructor of class 'Person' is public and it can be accessible within & outside of the class declaration.
Output you will get:
Now, If you don't want to access
class 'Person'
out side then you need to change public access modifiers to private and then that member can only accessible within the class declaration.Error you will get:
For more details please check this link typescriptlang access modifiers