JS private 如何使用

2016-02-27 02:11:22 +08:00
 kaiwei
最近看了道爷的 2001 文章
http://www.crockford.com/javascript/private.html
在自己的机器上跑,并没有 private 的效果啊。
```javascript
function Container(param) {
this.member = param;
var secret = 3;
var that = this;
}
var myContainer = new Container('abc');
console.log(myContainer.member); // 依然会打印 abc
myContainer.member = 'efg';
console.log(myContainer.member); // 会打印 efg
```
求解。多谢!
3031 次点击
所在节点    JavaScript
9 条回复
Septembers
2016-02-27 02:41:27 +08:00
Septembers
2016-02-27 02:43:26 +08:00
您认真看您发的文章了吗? secret 才是私有的啊
kaiwei
2016-02-27 04:49:10 +08:00
@Septembers 在 Private 那个标题下面:
This constructor makes three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.
他说,三个都是不能 accessible to the outside 。
xcodebuild
2016-02-27 08:58:14 +08:00
@kaiwei 你访问的是 member ,不是这三个的任何一个,有任何问题么?
yuriko
2016-02-27 09:14:14 +08:00
原谅我放荡不羁的笑点……
jsonline
2016-02-27 11:19:00 +08:00
为什么要把其它语言的概念搬到 JS
jkeylu
2016-02-27 11:27:20 +08:00
ES6 中 closure + Symbol 就能实现 private 的效果
neoblackcap
2016-02-28 01:01:02 +08:00
@kaiwei 如 @codefalling 所说你访问的是 member ,原文只说 param, secret, that 三个变量是私有的而已
xuzicn
2016-02-28 17:36:07 +08:00
额外插一句, JS 没有 private 这一说,想要实现数据保护经常引入额外的麻烦

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/259437

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX