V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
kaiwei
V2EX  ›  JavaScript

JS private 如何使用

  •  
  •   kaiwei · 2016-02-27 02:11:22 +08:00 · 2996 次点击
    这是一个创建于 2988 天前的主题,其中的信息可能已经有所发展或是发生改变。
    最近看了道爷的 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
    ```
    求解。多谢!
    9 条回复    2016-02-28 17:36:07 +08:00
    Septembers
        2
    Septembers  
       2016-02-27 02:43:26 +08:00 via Android
    您认真看您发的文章了吗? secret 才是私有的啊
    kaiwei
        3
    kaiwei  
    OP
       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
        4
    xcodebuild  
       2016-02-27 08:58:14 +08:00 via Android
    @kaiwei 你访问的是 member ,不是这三个的任何一个,有任何问题么?
    yuriko
        5
    yuriko  
       2016-02-27 09:14:14 +08:00
    原谅我放荡不羁的笑点……
    jsonline
        6
    jsonline  
       2016-02-27 11:19:00 +08:00 via Android
    为什么要把其它语言的概念搬到 JS
    jkeylu
        7
    jkeylu  
       2016-02-27 11:27:20 +08:00
    ES6 中 closure + Symbol 就能实现 private 的效果
    neoblackcap
        8
    neoblackcap  
       2016-02-28 01:01:02 +08:00 via iPhone
    @kaiwei 如 @codefalling 所说你访问的是 member ,原文只说 param, secret, that 三个变量是私有的而已
    xuzicn
        9
    xuzicn  
       2016-02-28 17:36:07 +08:00
    额外插一句, JS 没有 private 这一说,想要实现数据保护经常引入额外的麻烦
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   796 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:52 · PVG 03:52 · LAX 12:52 · JFK 15:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.