So I was reading some other thread about using dot notation to access an instance variable and a definition was the following:
By self.myVariable you are accessing the instance variable myVariable
and by myVariable you are accessing the local variable. They’re not
the same thing.
This seems to be very confusing to me, especially coming from a java background. Can someone explain to me clearly what he means by local variable here? Is this the same thing as using this in java? If it is the same then in java if say you have:
private int myVariable;
int testFunction(int m)
{
myVariable = 3;
}
This would access myVariable instance variable as there is no local variable defined in the method.
Self.myVariable does not access the instance variable (most of the time there won’t be a difference, there exceptions like when you have a custom setter). Instead it accesses the getter of the property. It is equivalent to:
If you want to access an instance variable directly you can use just:
If you want to access the instance variable of another object you can do:
Although as Caleb says below in the comments, this is frowned upon.