简体   繁体   English

如何在 Javascript 中实现封装

[英]How to Implement Encapsulation In Javascript

I am fairly new to Javascript and I was reading the docs and,我对 Javascript 相当陌生,我正在阅读文档,

According to MDN Docs:-根据 MDN 文档:-

Keeping an object's internal state private , and generally making a clear division between its public interface and its private internal state, is called encapsulation.对象的内部 state 保持私有,并且通常在其公共接口和其私有内部 state 之间进行明确的划分,称为封装。

They have not mentioned他们没有提到

How to keep an Object's Internal State Private?如何保持对象的内部 State 私有?

Also its mentioned further that,它还进一步提到,

In languages that don't enforce access like this, programmers use naming conventions, such as starting the name with an underscore, to indicate that the property should be considered private.在不强制访问这样的语言中,程序员使用命名约定,例如以下划线开头的名称,以指示该属性应被视为私有。

So what does this line mean那么这条线是什么意思

starting the name with an underscore, to indicate that the property should be considered private.名称以下划线开头,表示该属性应被视为私有。

Does this mean if I put _ before a property name it would become private, isn't there a difference between becoming private and making private.这是否意味着如果我将_放在属性名称之前,它将变为私有,私有化和私有化之间没有区别。 Does putting an underscore tells Javascript explicitly that this property is private?加下划线是否明确告诉 Javascript 该属性是私有的?

Also they have not provided any concrete code to explain that part I could only find the pseudocode他们也没有提供任何具体的代码来解释那部分我只能找到伪代码

class Student : extends Person
    properties
       year
    constructor
        Student(name, year)
    methods
       introduceSelf()
       canStudyArchery() { return this.year > 1 }

I googled this and found that closures are used to implement encapsulation behaviour, but the MDN Docs have not stated this anywhere Object-oriented_programming#encapsulation我用谷歌搜索了这个,发现闭包是用来实现封装行为的,但是 MDN 文档没有在任何地方说明这一点Object-oriented_programming#encapsulation

Question:- How to implement encapsulation in Javascript without closure can we use something like Object.freeze can someone explain with an example问题:-如何在 Javascript 中实现封装而不关闭我们可以使用类似Object.freeze的东西有人可以用一个例子来解释吗

Thank You.谢谢你。

Does this mean if I put _ before a property name it would become private这是否意味着如果我将 _ 放在属性名称之前,它将变为私有

No. _ before a field name is used to convey to the reader that these field(s) are meant to be private; No. _在使用字段名称之前向读者传达这些字段私有的; technically they are not private.从技术上讲,它们不是私有的。 Other code can access them and mutate them.其他代码可以访问它们并改变它们。

Fields that are truly private were recently introduced in the Javascript language.最近在 Javascript 语言中引入了真正私有的字段。

Before the above mentioned feature was introduced, Javascript devs used different techniques to implement private fields - using closures was one of them.在引入上述功能之前,Javascript 开发人员使用不同的技术来实现私有字段——使用闭包就是其中之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM