Private variables and functions in JavaScript
Private variables and functions in JavaScript:
Unlike Java/C#/AS3/PHP, JavaScript
doesn’t have keywords for defining if a variable/function/object is
private/public/protected/final/etc (assessor keywords)… But since it has
closures and each closure has its own scope we can emulate some of these access
controls, a private variable is simply a variable declared inside an
“unreachable scope”.
Example of function in javascript:
// global variable
var l = 'hello';
(function()
{
// the immediately invoked function expression (IIFE) will create a
closure
// all variable and functions inside this scope will be
"private"
var f = 'bar';
console.log(l); // 'hello'
console.log(f); // 'bar'
}
());
console.log(l); // 'hello'
console.log(f);
Because of this powerful and
useful language feature a lot of people been using design patterns like the
revealing module pattern to avoid polluting the global scope and to better
organize their applications (including myself).
Private variables are usually a
good thing since they avoid more problems than they cause, naming conflicts
(two pieces of code using same name to store different info) can be very hard
to track and it is very common to happen, that’s one of the main reasons why
people use so many private variables, but like most things in life it also has
it’s drawbacks and I’ll show a few cases where it can be an issue and how to
avoid it.
In other like Java/C#/AS3/PHP have
the concept of a protected class member, the protected member is like a private
one but that can be overwritten by a child class. By using protected on all
your members instead of using private you increase the flexibility of your
code, if the user wants to change the default behavior of a method he can
simply extend the class and overwrite it. The sad part is that private
variables in JS can’t be overwritten, not even by child classes.
Comments
Post a Comment