JavaScript Classes - How do you write them

Status
You're currently viewing only drogin's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

drogin

Ars Tribunus Angusticlavius
8,284
Subscriptor++
I write mine something like this:

Code:
var MyClass = function(options) {

    //more or less a static function
    var helper = function(arg1, arg2) {
        return arg1 + arg2;
    };

    //this is returning an actual instance of the class, but we wrap it in a function call to have real "private" members
    return function(){
        
        //locally scoped to the function and therefore private to this instance
        var _private1 = options.anotherThing;

        //this is the real instance, I promise. Lexical closure allows us to access our "private" variables
        return {
            getPrivate1 : function() { return _private1; },
            setPrivate1 : function(value) { _private1 = value; },
            doStuff : function(arg1) { var i = helper(arg1, _private1); return i; }
        };

    }(); //the parens are important because it invokes our anonymous function which returns our instance
};


var instance = new MyClass({ something : 1, somethingElse : 2, anotherThing : 3 });

//we get 9 because we _private1 should be 3 at this point
alert(instance.doStuff(6));
        
//notice how our value changes to 8? That's because we can modify _private1
instance.setPrivate1(2);
alert(instance.doStuff(6));
        
//we still get 8, because event though we defined _private1 on the class, our method are actually referencing the
//locally scoped _private1 via closure!
instance._private1 = 100;
alert(instance.doStuff(6));

As you can see from the above, doing it this way I get "private" members of the instance, as well as "static" members of the class.
 
Status
You're currently viewing only drogin's posts. Click here to go back to viewing the entire thread.
Not open for further replies.