Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Is it ok to return an object in Javascript class?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!