最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Private (#) getter in JavaScript - Stack Overflow

programmeradmin5浏览0评论

Are private getters/setters planned to be supported in JavaScript?

class Next {
  #private = 0
  get #puted() { // SyntaxError: Unexpected token (
    return this.#private + 1
  }
}

Are private getters/setters planned to be supported in JavaScript?

class Next {
  #private = 0
  get #puted() { // SyntaxError: Unexpected token (
    return this.#private + 1
  }
}

If not, what is the rationale behind that?
I suppose implementation wouldn't be a hurdle. Are there objections to the functionality itself?

Share Improve this question asked Apr 26, 2019 at 11:04 P VargaP Varga 20.2k13 gold badges77 silver badges118 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 12

Update - ECMAScript 2021

With the latest es2021 version Private getters and setters are also possible.

Your code should be valid now:

class Next {
  #private = 0
  get #puted() { 
   return this.#private + 1
  }
}

Yes, they're part of the private methods and accessors proposal, a follow-on to class fields. The syntax is exactly as you've shown it. JavaScript engines are actively working to implement them, and Babel has working transpilation for them via the @babel/plugin-proposal-private-methods plugin.

Those two proposals are joined by the static class features proposal which covers static public properties, static private fields, and static private methods (including accessors).

发布评论

评论列表(0)

  1. 暂无评论