Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

javascript - Accessing protected fields of base class from derived (ES2019 private class)

I'd like to access private fields of base class from derived classes without making them public (what is called 'protected' in other languages).

Consider the following class:

class Animal {

  #privateProp;

  constructor() {

  this.#privateProp = 12;

  }
}

Now the extending class:

class Cat extends Animal {

  constructor() {

    super();
  }

  doIt() {

    console.log(this.#privateProp) // 1 below
    console.log(super.#privateProp) // 2 below
  }
}

I'd like to execute as if it was protected:

new Cat().doIt();

But gets (respectively):

  1. Uncaught SyntaxError: Private field '#privateProp' must be declared in an enclosing class
  2. Uncaught SyntaxError: Unexpected private field

Notice that this code would work perfectly when privateProp becomes public, But I want to achieve a protected like behavior and get access to the 'private' fields like any language that support inheritance.

Any help will be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Fields are private in a similar way to how variables are block-scoped; if a property is private to a certain class, it may only be referenced inside that class. If you extend the class, it won't be visible in the derived class.

You could make a getter/setter on the superclass, if you want to be able to do stuff with it from the subclass:

class Animal {
  #privateProp = 12;
  setProp(val) {
    this.#privateProp = val;
  }
  getProp() {
    return this.#privateProp;
  }
}
class Cat extends Animal {
  doIt() {
    console.log(this.getProp());
  }
}
new Cat().doIt();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...