I'm having issues understanding scoping/access of fields defined with a JavaScript object.
Consider the following sample JavaScript object definition:
function SampleObject(controlName) {
var _controlName = controlName;
this.Display1 = function() {
console.log(_controlName);
}
this.Display2 = function() {
Display3();
}
Display3 = function () {
console.log(_controlName);
}
}
Now consider running the above object with the following example:
var a = new SampleObject("Bob");
var b = new SampleObject("Fred");
a.Display1(); //==> Displays "Bob"
b.Display1(); //==> Displays "Fred"
a.Display2(); //==> Displays "Fred"
b.Display2(); //==> Displays "Fred"
What I'm having difficulty understanding is how to access object fields (properties) from within private functions defined within my object. Within my example, I am confused as to why _controlName has the value "Fred" when it is displayed via Display2() for both objects a and b.
I suspect that is either an issue with how _controlName and/or Display3() is defined or I am unclear how scoping would work in this instance. Can someone please share some light on this?
Thanks,JohnB
thisin front ofDisplay3? By omitting this,Display3is global.thisin both places; the declaration and the call.