1

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?

9
  • 2
    What's the point of creating an object if you can't access its attributes or methods? Commented Oct 18, 2021 at 21:18
  • 2
    why do you want this? if the class does not returnitself, you get the custom object. Commented Oct 18, 2021 at 21:18
  • 1
    I neither understand what you mean by "for security" nor by "avoid accessing the class methods" Commented Oct 18, 2021 at 21:21
  • 1
    But you've effectively made everything private, since you never get the object. Commented Oct 18, 2021 at 21:22
  • 1
    @MHS ... "Assume everything operates automatically and does not need any public method" ... in that case a function, or, in order to meet the aspect of some lifetime, a closure are already sufficient enough. Commented Oct 18, 2021 at 21:32

1 Answer 1

5

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())

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.