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

154
Views
Private class variable declaration

I am trying declare a private class variable for a super class and I seem to have trouble doing so. I there something I am missing? This is my code so far.

class Animal {
  constructor(_name) {
      this._name = _name;
  }
  name() {
    console.log(`${this._name} is my name.`);
  }
}

new Animal('Bob').name();

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

0

Private fields start with # but their scope will keep them hidden from subclasses.

class Animal {
  #name
  constructor(name) {
      this.#name = name;
  }
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields

about 4 years ago · Juan Pablo Isaza Report

0

Private class features are available in the following browsers:

Chrome Edge FireFox Opera Safari
74+ 79+ 90+ 62+ 14.1+

Here is an example of your class with a private instance field called name:

class Animal {
  #name;

  constructor(name) {
      this.#name = name;
  }

  get name() {
    return this.#name;
  }

  toString() {
    return `${this.#name} is my name.`;
  }
}

const bob = new Animal('Bob');

console.log(bob.name);
console.log(bob.toString());

// console.log(bob.#name); <-- SyntaxError

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!