-
Notifications
You must be signed in to change notification settings - Fork 5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
private variables #8
Comments
There is no special build-in way. You can use lexical scoping, which is a common way in JavaScript to hide information. Example (run it online) function MakeTraitWithPrivateProperty(privateProperty) {
return Trait({
publicProperty: function () {
// do something with privateProperty
console.log("internal access: " + privateProperty)
}
})
}
var obj = Trait.create(
Object.prototype,
MakeTraitWithPrivateProperty(42)
);
console.log("external access: " + obj.privateProperty); // external access: undefined
obj.publicProperty(); // internal access: 42 The examples already cover this approach. |
@maiermic thank you. http://jsbin.com/dalexozohu/edit?js,console
Is this an OK approach to have state? I can't think of any issues with this |
@opcodewriter This approach with getters and setters is a very common OOP technique but has been criticized. |
@dotnetCarpenter thanks. but that's quite an article. I believe getters and setters are good for encapsulation. |
Your solution is fine just be aware of the following:
function MakeTraitWithPrivateProperty() {
var privateProperty = 42;
return Trait({
publicProperty: function () {
// do something with privateProperty
console.log("internal access: " + privateProperty);
},
add: function() {
privateProperty += 1;
}
});
}
var obj1 = MakeTraitWithPrivateProperty();
// do stuff with obj1
obj1.add(complexObject);
obj1 = null; // a private variable reference can still exist to `complexObject` The work-around is to define a ConclusionYou can use setter/getters but try to restrict yourself to primitive values, which are passed by-value (as oppose to by-reference). In JS primitives are, Number, String and Boolean. |
any example of private variables in a trait?
The text was updated successfully, but these errors were encountered: