javascript终于支持本机私有字段和方法

    科技2022-07-31  116

    JavaScript is known to be quite confusing for beginners as it contains some tricky concepts which require time and experience to fully master.

    众所周知,JavaScript对于初学者来说非常令人困惑,因为它包含一些棘手的概念,需要时间和经验才能完全掌握。

    One of the issue with the ES6 class implementation is that JavaScript did not contain a native way of implementing private variables. In other languages, you can either use the private keyword or use an _ in the variable to declare a private variable. Developers had to use workarounds such as using the underscore convention (_propertyName), Closures, Symbols, or WeakMaps.

    ES6类实现的问题之一是JavaScript不包含实现私有变量的本机方式。 在其他语言中,可以在变量中使用private关键字或使用_来声明私有变量。 开发人员必须使用变通方法,例如使用下划线约定 ( _propertyName ), Closures , Symbols或WeakMaps 。

    Although an underscore provides a hint to the developer, there’s nothing preventing them from accessing that property.

    尽管下划线为开发人员提供了提示,但没有什么可以阻止他们访问该属性。

    But thankfully, a newer TC39 proposal that allows defining private class fields by simply using a hash # has been in development for quite some time. It has reached stage 3 successfully. Let’s have a look at these newer private class fields.

    但值得庆幸的是,已经有相当长的一段时间开发了一个新的TC39提案,该提案允许仅通过使用#来定义私有类字段。 它已成功进入第三阶段。 让我们看一下这些较新的私有类字段。

    Share your reusable components between projects using Bit (Github). Bit makes it simple to share, document, and organize independent components from any project.

    使用 Bit ( Github ) 在项目之间共享您的可重用组件 。 Bit使共享,记录和组织来自任何项目的独立组件变得简单。

    Use it to maximize code reuse, collaborate on independent components, and build apps that scale.

    使用它可以最大程度地重复使用代码,在独立组件上进行协作以及构建可扩展的应用程序。

    Bit supports Node, TypeScript, React, Vue, Angular, and more.

    Bit支持Node,TypeScript,React,Vue,Angular等。

    Example: exploring reusable React components shared on Bit.dev 示例:探索在 Bit.dev上共享的可重用React组件

    专用静态字段 (Private Static Fields)

    Private static fields can be accessed from within the class declaration itself. These fields still follow the tradition where they can only be called from a static method.

    可以从类声明本身内部访问私有静态字段。 这些字段仍然遵循只能通过静态方法调用的传统。

    Code Snippet by Author 作者的代码片段

    However, private static fields can only be accessed from the class which defined the field. Take a look at the below code.

    但是,只能从定义字段的类中访问私有静态字段。 看下面的代码。

    Code Snippet by Author 作者的代码片段

    The above code is different from the initial code as it accesses the private static variables using this keyword. Although this works in the above example, it would cause errors when the variable is accessed from a child class.

    上面的代码与初始代码不同,因为它使用this关键字访问私有静态变量。 尽管这在上面的示例中有效,但是从子类访问变量时会导致错误。

    Code Snippet by Author 作者的代码片段

    To avoid this issue, we should always avoid using the this keyword in this situation.

    为避免此问题,在这种情况下,我们应始终避免使用this关键字。

    Code Snippet by Author 作者的代码片段

    私有实例字段 (Private Instance Fields)

    Private instance fields are simple and straight to the point. You declare a private instance variable by using the #. This approach is called ‘# names’ which is simply, identifiers prefixed with a #. It should also be noted that the hash is part of the name itself, as you would need to use it when declaring and accessing the private instance variable.

    私有实例字段简单明了。 您可以使用#声明一个私有实例变量。 这种方法被称为“#姓名”这简直是,与前缀标识符# 。 还应注意,哈希是名称本身的一部分,因为在声明和访问私有实例变量时需要使用它。

    You will receive a syntax error when you try to access a private instance variable outside of its scope. You should also make sure the private instance variables are declared before assigning values or accessing them.

    当您尝试访问其范围之外的私有实例变量时,将收到语法错误。 您还应确保在分配值或访问它们之前,已声明私有实例变量。

    Code Snippet by Author 作者的代码片段

    私有静态方法 (Private Static Methods)

    Similar to the private static variables, private static methods can only be called from within the class itself. Similarly, they can only be accessed from within the class declaration.

    与私有静态变量类似,私有静态方法只能从类本身内部调用。 同样,只能从类声明中访问它们。

    Code Snippet by Author 作者的代码片段

    Likewise, if you use the this keyword to access the static methods like the below code, you might fall into trouble when child classes come into action.

    同样,如果使用this关键字访问类似于以下代码的静态方法,则子类生效时可能会遇到麻烦。

    Code Snippet by Author 作者的代码片段

    The below example will cause errors as the keyword this refers to the SubClass when we call SubClass.publicStaticMethodInDemoClass . As the private static method is called from outside of its scope(DemoClass), you will receive an error.

    下面的例子将导致错误的关键字this指的是当我们调用子类SubClass.publicStaticMethodInDemoClass 。 由于从其作用域(DemoClass)外部调用了私有静态方法,因此您将收到一个错误。

    Code Snippet by Author 作者的代码片段

    To avoid the above error, always avoid referring to this when calling a private static field or method.

    为避免上述错误,在调用私有静态字段或方法时,始终避免引用this 。

    Code Snippet by Author 作者的代码片段

    私有实例方法 (Private Instance Methods)

    Similar to the private instance variables, private instance methods can only be accessed from within the class which declared the method.

    与私有实例变量类似,私有实例方法只能从声明该方法的类中访问。

    Code Snippet by Author 作者的代码片段

    批评 (Criticisms)

    There are some criticisms put forth by Warren Parad against the above proposal. Let's have a look at some of these criticisms.

    沃伦·帕拉德 ( Warren Parad)对上述提议提出了一些批评。 让我们看一下其中的一些批评。

    1.以上提议允许 private 域 和 public 域同时存在相同名称。 (1. The above proposal allows for private and public fields to exist with the same name at the same time.)

    Jamie mentions that this behaviour is intentional. The reason is that they want to keep the variables as “hard private”.

    杰米提到这种行为是故意的。 原因是他们希望将变量保留为“硬私有”。

    “Further, to be truly private, you shouldn’t be able to even detect that a private field exists. In order to make sure that you can’t detect a private field, we need to allow public fields with the same name.” — Jamie

    “此外,要真正成为私有用户,您甚至应该无法检测到存在私有字段。 为了确保您无法检测到私有字段,我们需要允许使用相同名称的公共字段。” — 杰米

    2.您不能通过 this['field'] 访问私有字段 (2. You cannot access private fields via this['field'])

    Public fields in JavaScript can be accessed either via this.field or this[‘field’] .

    可以通过this.field或this['field']访问JavaScript中的公共字段。

    3.支持此语句。 (3. This statement is supported.)

    this.#x === other.#x && this.#y === other.#y;

    this.#x === other.#x && this.#y === other.#y;

    Have a look at the below example.

    看下面的例子。

    class Point { #x; #y; constructor(x, y) { this.#x = x; this.#y = y; } equals(otherPoint) { return this.#x === otherPoint.#x && this.#y === otherPoint.#y; }}

    The Point class works well for the below example.

    Point类在以下示例中效果很好。

    const point1 = new Point(1,2);const point2 = new Point(2,3);const point3 = new Point(1,2);point1.equals(point2);//falsepoint1.equals(point3);//true

    But what if, the parameter passed is not a Point? You will get a TypeError. This means you have to additionally check whether the parameter is of instance Point.

    但是,如果传递的参数不是Point怎么办? 您将收到TypeError。 这意味着您必须另外检查参数是否为实例Point。

    The team mentions that the above pattern is allowed in other languages. The below code is a similar example from Java.

    团队提到其他语言也允许使用上述模式。 以下代码是Java的类似示例。

    class Point { private int x = 0; private int y = 0; public boolean equals(Point p) { return this.x == p.x && this.y == p.y; }}

    Unlike the JS example, you cannot pass an object which is not an instance of the Point class in the above example. This is due to the fact Java is a statically typed language. The same is not possible in the JavaScript version of the code as JS is a dynamically typed language.

    与JS示例不同,在上面的示例中,您不能传递不是Point类实例的对象。 这是由于Java是一种静态类型的语言。 在JavaScript版本的代码中,这是不可能的,因为JS是一种动态类型的语言。

    浏览器兼容性 (Browser compatibility)

    Browser Compatibility — Screenshot by Author 浏览器兼容性—作者的屏幕截图

    That’s it for this article. If you would like to share your views and comments, please do comment below.

    本文就是这样。 如果您想分享您的看法和评论,请在下面发表评论。

    Thank you for reading & Happy Coding!!

    感谢您的阅读和快乐编码!

    学到更多 (Learn More)

    ResourcesMDN DocsTC39 ProposalsArticle by Warren ParadArticle by Jamie

    资源 MDN文档 TC39提案 沃伦·帕拉德(Warren Parad) 文章,杰米(Jamie)

    翻译自: https://blog.bitsrc.io/javascript-finally-has-support-for-native-private-fields-and-methods-d758fdcfd320

    相关资源:微信小程序源码-合集6.rar
    Processed: 0.015, SQL: 8