What happens if return an object when defining a class constructor? can I use it for security and avoid accessing the class methods and ...?
for example I have below code:
class X {
y = ''
x = 0
constructor(
p1,
p2,
) {
this.p1 = p1
this.p2 = p2
return {
getp1: this.getp1
}
}
getp1 = () => this.p1
}
let x = new X("fo", "bar")
console.log(x.p1) // will be undefined
console.log(x.getp1() ) // will be "fo"
as you see x.p1 is not accessible directly, but I can get p1 by getp1 method. can I use it for private and public methods in javascript?
This would be a better approach.
You can use # to make a property or a method "private" which means it can only be accessed by methods or properties inside of that class. the code below demonstrates its usage
class Test {
#privateValue;
constructor() {
this.#privateValue = 10;
}
test() {
return this.#privateValue;
}
}
const test = new Test();
console.log(test.privateValue)
console.log(test.test())