I'm trying to understand how the this
keyword works.
This article The this keyword states
"In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of."
function someClosure() {
var myVal0, myVal1, myVal2;
init = function (myVal0, myVal1, myVal2) {
myVal0 = myVal0;
this.myVal1 = myVal1;
this.myVal2 = myVal2;
};
getMyVal0 = function() { return myVal0 };
getMyVal1 = function() { return myVal1 }
getMyVal2 = function() { return this.myVal2 }
};
I surmise that getMyVal0
is undefined
after init()
is called because of a naming clash (the assignment is ambiguous).
But (after calling init()
) why does getMyVal1
return undefined
? The reference to myVal1
should not be ambiguous. Does Javascript require an explicit use of this
? getMyVal2
returns the expected value, but again, I'm surprised that I need the explicit this
.
Please clarify this behavior.
Ultimately, I'm trying to establish a naming convention for function arguments when initializing member variables. By industry convention, IRR is IRR and it seems this
should allow me to avoid comming up with two names for a variable (without always referencing the member variable with this
.) What's the convention for doing what I want to do?
init
and thegetMyVal
functions withvar
that you're creating global variables, right?