Reputation: 2059
We know when we are using Object Literals or when we employ Object.Create() to inherit a new Object of a parent one, the child object inherit all the properties and functions of the parent object.
So, how we can hide the private members form the inherited class?
So if we can't, it means using function as class and the "new" keyword to inherit from the parent class, is the only way to reach the ENCAPSULATION in JavaScript!
Upvotes: 1
Views: 294
Reputation: 49714
The short answer is No. All properties in Object literals are public (at least as of ES5).
That said, thanks to lexical scoping, Encapsulation does exist in Javascript, and can be achieved through the use of closures.
For example, the object returned by myObjectWithPrivateMembers
has access to an encapsulated property, value
, which is not publicly visible/accessible (because that object is defined within a closure).
function myObjectWithPrivateMembers() {
var value = 1;
var addOne = function() {
value++;
};
var getValue = function() {
return value;
};
return {
addOne: addOne,
getValue: getValue
};
}
var test = myObjectWithPrivateMembers();
test.value; // undefined
test.getValue(); // 1
test.addOne();
test.getValue(); // 2
Upvotes: 1
Reputation: 11607
The easiest way to obtain encapsulation are functions or anonymous functions (closures). This is an example of information hiding and getter/setter logic while classical JS (not ES6/Harmony) does not apparently support it:
var obj = (function () {
var hidden;
hidden = 1973;
return {
"get": function () { return hidden; },
"set": function (v) { hidden = v; }
};
}()); // define and execute right away
You can now use obj
as follows:
obj.get() // returns the hidden value
obj.set(1982) // sets the hidden value
Demonstration of information hiding:
obj.hidden // no dice
OO programming in JS does not really support classical inheritance. It supports prototypical inheritance which has its differences.
Upvotes: 1