In most of our programming languages like C#, C++, Java etc, we use
this keyword to denote current object we are working on.
So, how does the code above work?
what it does internally, look something similar to this:
this keyword. If our given function returns anything then it sets our instantiated variable with the returned value otherwise sets the generic object created.
Let me give you an example with a code
Explanation: So, we have a function
showHello and a private variable and a nested-function where this function is a closure as it has reference to the outer scope’s members, and then we return the reference of the nested-function
showAlert and preserving it in
showAlertReference variable, and then we invoke
showAlertReference which is only a reference to the nested-function
showAlert having only the
showAlert function is sent!
Hope this helped! But you should consider seriously about the Jim Ley’s article I noted above!
Back to private members
Private members are nothing but closures here! Look at the code below!
We are actually simulating the private/public members/methods by using closures! Again, when
this keyword inside the
person function! As
_name is not being set on the object passed as
this and thus
_name is just acting like a local variable of the function person and the methods (
setName) inside the person function are set to the object passed as this and due to closure, invoking the methods (
setName) can have access to
_name variable which should have died when person function expired!