0

I'm creating a namespace and are wondering how I can restrict accessibility to a namespace variable so that it only can be accessed from inside the namespace.

In my sample code I want PrivateExec to be private and not accessible outside the namespace.

var demo = {
    a: "demo",
    b: {
        PrivateExec: function () {
            //execute
        },
        ExecA: function () {
            PrivateExec();
        },
        ExecB: function () {
            PrivateExec();
        }
    }
}

demo.ExecA(); //success
demo.PrivateExec(); //fails because of private
Chin Leung
  • 14,621
  • 3
  • 34
  • 58
SteinTheRuler
  • 3,549
  • 4
  • 35
  • 71
  • 2
    Possible duplicate of [Private properties in JavaScript ES6 classes](https://stackoverflow.com/questions/22156326/private-properties-in-javascript-es6-classes) – Jared Smith Nov 09 '17 at 19:29
  • 1
    I'd highly recommend reading "Learning JavaScript Design Patterns" (https://addyosmani.com/resources/essentialjsdesignpatterns/book/) for pre-ES6. See the "Module" pattern for an example of private methods. – John Ellmore Nov 09 '17 at 19:29
  • *Why* does it have to be private? – Jared Smith Nov 09 '17 at 19:30
  • 1
    With how you are doing it, not going to happen. – epascarello Nov 09 '17 at 19:31

1 Answers1

-2

Try NOT using this code: Your variable should be private !

var value = Symbol();
class MyClass {
    constructor(){
        this[value] = "this is a test string";
    }
}

var call = new MyClass();

console.log(call.value); // should be undefined
Jonas0000
  • 1,085
  • 1
  • 12
  • 36
  • 1. - 2. It is kind of private, sure. Yeah `call.value` is undefined. Do you know why? - BECAUSE ITS PRIVATE! @JaredSmith – Jonas0000 Nov 09 '17 at 19:34
  • `call[value]` will still give you the string. `Object.getOwnPropertySymbols(call)` will still get you the string. Not private. – Jared Smith Nov 09 '17 at 19:35
  • I have to agree with @JaredSmith here. The only way to have proper private stuff (in the sense "not accessible from the outside world") is to play with scopes. – sp00m Nov 09 '17 at 19:39
  • You can not create PRIVATE variables. You have to use scopes like sp00m mentioned. But I've edited my answer @JaredSmith :) – Jonas0000 Nov 09 '17 at 19:40
  • 1
    @sp00m eh, native modules get you there, but that limits your clients. – Jared Smith Nov 09 '17 at 19:41
  • 1
    @JaredSmith Good old IIFE FTW! – sp00m Nov 09 '17 at 19:42