I am a JS newbie, reading a book Javascript Patterns for understanding. One of the code snippets I could see :
var myFunc = function param() {
...
...
};
myFu
Doesn't this break encapsulation ?
Yes and no. If you use a closure, you can still have "private" variables in the sense that they cannot be accessed from outside of the object's functions as declared at instantiation time. Example:
var ObjectPrototype = function () {
var privateVariable = "closure-scope value";
var InnerPrototype = function () {
this.getPrivate = function () { return privateVariable; };
};
return new InnerPrototype();
};
var myObject = new ObjectPrototype();
Because the ObjectPrototype
returns a new instance of the InnerPrototype
, and privateVariable
exists only within the ObjectPrototype
closure, there is no way to access privateVariable
directly from the outside. The only way to get the value of it is through myObject.getPrivate()
.
Note: Javascript passes objects and arrays by reference, so this method only truly protects simple values (unless you are careful to return clones instead).
What if some other part of program keeps on adding new properties making my object creation bulky ?
That is something that you'll just need to keep an eye on.
What if someone deletes/modifies properties defined by me ?
Use the closure-scoping method I described above to prevent this.