I'm working on a utility to create classes in javascript. And it works, the problem is how to define private attributes.
This is the code
var OO = {
Class:function(){
var len = arguments.length;
var data = arguments[len-1];
var Klass;
if (data.constructor === Object){
Klass = function (){};
} else {
Klass = data.constructor;
delete data.constructor;
}
OO.extend(Klass.prototype,data); //Classic Extend Method
return Klass;
},
//Simple extend method, just what I need in this case
extend: function(target, source){
var prop;
for (prop in source)
target[prop] = source [prop];
}
}
This is how it works
// first create a class
var person = OO.Class ({
constructor: function (name, age) {
this.name = name;
this.age = age;
},
name:'',
age:'',
getName: function () {
return this.name;
},
getAge: function () {
return this.age;
}
});
And here is the instance
var one = new Person ('josh', 22);
And the problem:
one.age / / returns 22
one.name / / returns josh
What I need is that these properties can only be accessed by methods like getName () and getAge ()
EDIT1: Added Extend Function
Class fields are public by default, but private class members can be created by using a hash # prefix. The privacy encapsulation of these class features is enforced by JavaScript itself.
Short answer, no, there is no native support for private properties with ES6 classes. But you could mimic that behaviour by not attaching the new properties to the object, but keeping them inside a class constructor, and use getters and setters to reach the hidden properties.
The classic way to make class methods private is to open the eigenclass and use the private keyword on the instance methods of the eigenclass — which is what you commonly refer to as class methods.
Private class fields are a Stage 3 TC39 proposal. Even though they're still experimental, you can use private class fields in Node. js 12 without flags or transpilers.
The closure is created by the constructor params, so this is all you need to do (edited AlienWebguy's code):
var Person = function(name, age){
this.getName = function() {
return name;
};
this.getAge = function() {
return age;
};
};
var john = new Person('johnathan', 33);
document.writeln(john.name); // undefined
document.writeln(john.age); // undefined
document.writeln(john.getName()); // johnathan
document.writeln(john.getAge()); // 33
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With