Hady
Hady

Reputation: 2664

Class variable in javascript class

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 );

Upvotes: 1

Views: 2485

Answers (3)

Helgi
Helgi

Reputation: 1577

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?

Upvotes: 5

Steerpike
Steerpike

Reputation: 17544

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.

Upvotes: 0

KooiInc
KooiInc

Reputation: 122888

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

window.globalVar = somevalue
globalVar = somevalue

Upvotes: 1

Related Questions