Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to access private constructor-scoped variables from a functions prototype?

Based on my understanding of javascript, prototype methods cannot access variables that are private to the scope of the constructor,

 var Foo = function() {
      var myprivate = 'I am private';    
      this.mypublic = 'I am public';
 }

 Foo.prototype = {
     alertPublic: function() { alert(this.mypublic); } // will work
     alertPrivate: function() { alert(myprivate); } // won't work
 }

It makes perfect sense, but is there any way around this that is safe and good practice? Since using prototypes provides a performance benefit in that the member functions are allocated only once, I'd like to achieve a similar functionality while still being able to get to my private variables. I don't think it will work by using a prototype, but is there another pattern, such as a factory method or a closure approach? Something like,

var fooFactory = function() {
    var _alertPrivate = function(p) { alert(p); } // bulk of the logic goes here
    return function(args) {
         var foo = {}; 
         var myprivate = args.someVar; 
         foo.mypublic = args.someOtherVar; 
         foo.alertPrivate = function() { _alertPrivate(myprivate); };
         return foo; 
    }; 
}

var makeFoo = new fooFactory();
var foo = makeFoo(args); 

I'm not sure whether a new copy of _alertPrivate is created each time I create a new Foo or if there is any potential performance benefit. The intention is to get a functionality similar to prototyping (inasmuch as it saves memory) while still being able to access private variables.

Thanks.

like image 558
Sean Thoman Avatar asked Oct 16 '11 23:10

Sean Thoman


1 Answers

I have come up with the following pattern to address this issue, atleast for now. What I needed was a privileged setter so that a private variable could be changed from inside certain prototype functions but not from anywhere else:

 var Foo = (function() {

    // the bulk of the objects behavior goes here and is created once 
    var functions = {
        update: function(a) {
             a['privateVar'] = "Private variable set from the prototype";
        }
    }; 

    // the objects prototype, also created once
    var proto = {
        Update: function() {
             this.caller('update'); 
        }
    };

    // special function to get private vars into scope
    var hoist = function(accessor) {
        return function(key) {
             return functions[key](accessor()); 
        }
    }

    // the constructor itself
    var foo = function foo() {
        var state = {
            privateVar: "Private variable set in constructor",
            // put more private vars here
        }
        this.caller = hoist(function(){
            return state;
        }); 
    }

    // assign the prototype
    foo.prototype = proto;

    // return the constructor
    return foo; 

 })(); 

Basically a pointer to the objects internal state is hoisted to its prototype via a closure over a simple accessor function() { return state; }. Using the 'caller' function on any given instance allows you to call functions which are created only once but can still refer to the private state held in that instance. Its also important to note that no functions outside of the prototype could ever access the privileged accessor, since the 'caller' only accepts a key that refers back to the predefined functions which are in scope.

Here are some benchmarks of this method to see how it compares to pure prototyping. These figures represent creating 80,000 instances of the object in a loop (note the object used for benchmarking is more complex than the one above, which was just for simplification purposes):

CHROME:

Closure Only - 2172ms

Prototyping (above way) - 822ms

Prototyping (std way) - 751ms

FIREFOX:

Closure Only - 1528ms

Prototyping (above way) - 971ms

Prototyping (std way) - 752ms

As you can see the method is almost as fast as normal prototyping, and definitely faster than just using a normal closure that copies functions along with the instance.

like image 184
Sean Thoman Avatar answered Sep 27 '22 23:09

Sean Thoman