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

查看:168
本文介绍了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:


  • 使用模块。模块中的所有内容都是私有的,除非使用 export 关键字公开。

  • =http://www.kirupa.com/html5/closures_in_javascript.html> http://www.kirupa.com/html5/closures_in_javascript.htm

  • 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规范中的隐私是真实的,但不再是这样:https://mail.mozilla.org/pipermail/es-discuss/2014-January/035604.html http://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 http://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天全站免登陆