Toma Tomov
Toma Tomov

Reputation: 1652

Is this a right way to set variables as private

Is this a right way to set a variables as private?

function test(a, b){
        let aa = a
        let bb = b
        return {
            getA: () => {
                return aa
            },
            getB: () => {
                return bb
            }
        }
    }

Now I can't access aa and bb directrly. And if I put this keyword infront of the variables, will it be accepted as an object? I know that in JavaScript functions are objects but it become more like object syntax. I am confused a lot from all the JavaScript options. It seems like there is no conventions in anything. The this type:

function test(a, b){
        this.aa = a
        this.bb = b
        return {
            getA: () => {
                return this.aa
            },
            getB: () => {
                return this.bb
            }
        }
    }

Both examples seems equal to me. The summed question - Is the privace of those variables is achieved in those ways ?

Upvotes: 0

Views: 73

Answers (1)

Liam
Liam

Reputation: 29674

These blocks of code are not equal. See below:

function test(a, b){
        let aa = a
        let bb = b
        return {
            getA: () => {
                return aa
            },
            getB: () => {
                return bb
            }
        }
    }
    
let testResult = test(1, 2);
console.log(testResult.aa)
//error
console.log(aa);

vs

function test(a, b){
        //this here === window
        this.aa = a
        this.bb = b
        return {
            getA: () => {
                return this.aa
            },
            getB: () => {
                return this.bb
            }
        }
    }
    
let testResult = test(1,2);
console.log(testResult.aa);
//can get aa
console.log(aa);

this in your second block of code is the window object. So aa is not private. Where as in the first block, it's block scoped and not accessible. So aa is only "private" in the first one.

Is this the "right" way?

As I mentioned this is just a design pattern (revealing module pattern). Be wary of "right" way. "right" is subjective and depends on context. There is no "right" way, but this is a common way of structuring this kind of thing.

This is just using a closure to scope a variable. There is no "private" declaration, as such, in js. Just scoped variables.

Upvotes: 1

Related Questions