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?
Read this introduction to the
thiskeyword at MDN.The value of
thisdepends on how you call the function. But you don’t call theinitat all, and all variables are stillundefined.No.
thisin JavaScript is different fromthisin other languages like Java. It will not let you access variables from a higher scope. In your case, the arguments of theinitfunction just shadow the variables frommyClosure– you can’t access them. You need to rename them if you want them. Use this script:Btw, you might combine the
closureandinitcall to only one function: