JavaScript ES6类中的私有属性 [英] Private properties in JavaScript ES6 classes

查看:150
本文介绍了JavaScript ES6类中的私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在ES6类中创建私有属性吗?

Is it possible to create private properties in ES6 classes?

这是一个例子。
如何阻止访问 instance.property

class Something {
  constructor(){
    this.property = "test";
  }
}

var instance = new Something();
console.log(instance.property); //=> "test"


推荐答案

答案是否。但您可以创建私人访问属性,如下所示:

The answer is "No". But you can create private access to properties like this:

  • Use modules. Everything in a module is private unless it's made public by using the export keyword.
  • Inside modules, use function closure: http://www.kirupa.com/html5/closures_in_javascript.htm

(在较早版本的ES6规范中可以使用Symbols来确保隐私的建议,但不再如此: https://mail.mozilla.org/pipermail/es-discuss/2014-January /035604.html https://stackoverflow.com/a/22280202/1282216 。对于更长的时间关于符号和隐私的讨论请参见: https://curiosity-driven.org/private-properties -in-javascript

(The suggestion that Symbols could be used to ensure privacy was true in an earlier version of the ES6 spec but is no longer the case:https://mail.mozilla.org/pipermail/es-discuss/2014-January/035604.html and https://stackoverflow.com/a/22280202/1282216. For a longer discussion about Symbols and privacy see: https://curiosity-driven.org/private-properties-in-javascript)

这篇关于JavaScript ES6类中的私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆