views:

276

answers:

3

The solution to this question suggested the use of John Resig's class implementation. This solution covers all my needs except:

How to declare a public global variable inside this class that can be accessed from outside?

I would like to establish something like the following:

    var MyClass = Class.extend({

        EVENT_NAME : 'event-name',

        init : function() {
            // ...
        }

    });

// Now another file can directly read this value without creating the class object
console.log( MyClass.EVENT_NAME );
+1  A: 

Declare it in the window context or don't use the 'var' keyword:

window.globalVar = somevalue
globalVar = somevalue
KooiInc
yip, that is my fall back plan. But my preference would be to have it with its class that 'owns' it.
Hady
A: 
var MyClass = Class.extend({

        EVENT_NAME : 'event-name',

        init : function() {
            // ...
        }
        return {
            event_name: function() { return EVENT_NAME; }
        }

    });
    console.log( MyClass.event_name );

Actually, to be honest, I'm not sure how the above is going to work with .extend() as I've not actually used extend() before. However, the return { name:value } technique is a pretty common way of exposing public instance methods in objects. It shouldn't take long to test it properly, sorry I didn't have a chance to do it myself.

Steerpike
I'll also just point out that currently the EVENT_NAME : 'event-name' that you have *is* a global variable, as you don't have 'var' in front of it.
Steerpike
+3  A: 

The "only" way to do what you want to do is to use a function as the "class". This way you are declaring a "class" whose public "static" members can be accessed. Something like this:

function MyObject() {
  // constructor stuff here
}
MyObject.EVENT_NAME = "event_name";

console.log(MyObject.EVENT_NAME); // No need to instantiate MyObject

However, seems to me like you are mixing concepts from statically typed languages with Javascript's more dynamic stuff. Why would you want to access a member of an object that has not been created?

Helgi
there's plenty of reasons, and there's examples baked into Javascript already: look at all the static members and methods on the Math class: Math.PI, Math.round() etc. It's just basic namespacing and it's a really good idea if you want to avoid conflicts.
nickf
That I understand, but what you basically said was that you wanted to access a member of a "class" before it was defined/created.
Helgi
There is a need for me to declare static field variables in my class. Other classes that use the MyObject need to do various comparisons over it (if that makes any sense). nickf mentioned a good example of Math.PI being one example.
Hady