Underscore prefix for property and method names in JavaScript

后端 未结 6 1732
误落风尘
误落风尘 2020-11-22 16:26

Is the underscore prefix in JavaScript only a convention, like for example in Python private class methods are?

From the 2.7 Python documentation:

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 16:49

    Welcome to 2019!

    It appears a proposal to extend class syntax to allow for # prefixed variable to be private was accepted. Chrome 74 ships with this support.

    _ prefixed variable names are considered private by convention but are still public.

    This syntax tries to be both terse and intuitive, although it's rather different from other programming languages.

    Why was the sigil # chosen, among all the Unicode code points?

    • @ was the initial favorite, but it was taken by decorators. TC39 considered swapping decorators and private state sigils, but the committee decided to defer to the existing usage of transpiler users.
    • _ would cause compatibility issues with existing JavaScript code, which has allowed _ at the start of an identifier or (public) property name for a long time.

    This proposal reached Stage 3 in July 2017. Since that time, there has been extensive thought and lengthy discussion about various alternatives. In the end, this thought process and continued community engagement led to renewed consensus on the proposal in this repository. Based on that consensus, implementations are moving forward on this proposal.

    See https://caniuse.com/#feat=mdn-javascript_classes_private_class_fields

提交回复
热议问题