javascriptprivate-membersprivileged-functions

is there a way to inject privileged methods after an object is constructed?


I'm trying to write fully automated unit tests in JavaScript and I'm looking for a way to read some private variables in various JS functions. I thought I recalled a way to inject privileged members into a function/object (and found an overwhelming occurrence of "no such thing as private in JS") and yet I can't find any resources indicating how.

I'm trying to read through the properties of .prototype but if there's a way, someone out here would know where to direct me faster than I'd find on my own.

Thanks

Update

  1. Privileged means a function that is usable from outside an object and has access to read "private" variables (variables otherwise unable to read from outside). See http://javascript.crockford.com/private.html for Crockford's explanations.

  2. A sample of the function I'm trying to inject to is o2, where I need to validate the value of x (this is a simplified example, the actual code does some transformations and sends them off to other functions which I plan on testing separately).

    var o2 = function() {
        var x = 'me';
    };
    

Update 2: Thanks to everyone who's taken the time to respond. I'm seeing that the overwhelming response here is, "private is private" despite the commentary I see in other SA questions where people say "nothing in JS is private". I guess that is more like rhetorical commentary rather than what I was hoping was some kind of insight into a potential loophole I didn't yet know about.


Solution

  • Correct answer to your question

    Even if we try to help you as much as we can, the correct answer to your question is simple:

    ...you can't

    What good would closure variables be if we could access them directly from outside of closure?

    if you had an object with private variables, they wouldn't be accessible outside function closure, which is the constructor function.

    var c = function() {
        var priv = "private";
        this.get = function() {
            return priv;
        };
    }
    
    var o = new c();
    o.injected = function() {
        return priv; // ERROR!!!!!! priv doesn't exist in function scope
    };
    

    It is of course different matter if you enclose the whole thing inside a function closure but then you wouldn't have object privates, but rather function closure internals that would be shared among all prototypes within this closure.

    (function(){
    
        var intrn = "internal";
    
        // omit "var" to make it global
        c = function() {
            this.get = function() {
                return intrn;
            };
        };
    
        // omit "var" to make it global
        o = new c();
        o.injected = function() {
            return intrn; // WORKS
        };
    })();
    
    o.injected();
    

    but this is different than object privates...