Tag Archives: Accessing Private

OOP JavaScript: Accessing Public Methods in Private Methods

As you know in JavaScript when you define a variable with the special word “var” the scope of this variable is within the function. So when you simply wite “var a = 5” the variable named “a” has a global scope and can be accessed in any function in the global scope.

var a = 5;
 
function f() { return a; } // returns 5

Thus f will return the value of “a” which equals to 5. You can also change the value of the global variable in the function body.

var a = 5;
function f() { a = 10; return a; }
console.log(a); // equals to 10

Now after we call the function f the value of “a” will equal to 10. This is because we reference the global variable “a” into the function body without using the keyword “var”. This means that if you put the “var” keyword the variable “a” inside the function body is no longer the same variable as the variable defined outside the body. It becames “local” and it’s visible only inside the function.
Continue reading OOP JavaScript: Accessing Public Methods in Private Methods