0

I'm trying to create a class to better organize my code, I decided to go the object literal route

var MyClass = {

}

I'm currently running into issues migrating some of my functionality though, previously I had global scope variables Channels for example set to an object instance. Is there a way to still do this in javascript within a class without moving the object into global scope?

var Prime = {
   Channel: new __Prime__Channel(),

   //The object in question
   __Prime__Channel: function() {
       this.Property = Value;
   },
}

this throws

Undefined reference __Prime__Channel() at line 2

In global scope you could do

var Channel = new __Prime__Channel();

function __Prime__Channel() {
        this.Property = Value;
}

without any errors

  • 1
    "to still do this" - do what? – Igor Dec 28 '16 at 19:55
  • It is not clear what you are asking. Can you show the old-style working code and the *same* functionality you try to implement in a different way? NB: `var Prime{` is invalid syntax. – trincot Dec 28 '16 at 19:56
  • If you were to run this __Prime__Channel is undefined Im asking if there is a way to set the class variable to a new instance of the class function – HyperCrusher Dec 28 '16 at 19:58
  • I don't understand what you are saying. Can you show the old-style working code and the same functionality you try to implement in a different way? – trincot Dec 28 '16 at 20:01
  • Sure, I added what I have been doing in global scope, but when you limit the scope to within the class via var Prime you get an undefined error – HyperCrusher Dec 28 '16 at 20:02

1 Answers1

0

An object is no class, please ensure you're using the right terminology.

With an object literal it is not possible to do what you want, the only way is

var Prime = {
   __Prime__Channel: function() {
       this.Property = Value;
   }
}
Prime.Channel = new Prime.__Prime__Channel();

However, maybe an object literal is the wrong pattern anyway. If you want to avoid global variables, look into the module pattern and IIFEs.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks, my project is limited by a javascript interpreter thats fairly out-fo-date and I have no control over so I'm stuck using object literals as "classes" sorry for the mix-up in terminology – HyperCrusher Dec 28 '16 at 20:11
  • Nah, you can have "classes" since ES1 with constructors and prototypes, but `Prime` really is neither. `Prime.__Prime__Channel` might be called a "class". – Bergi Dec 28 '16 at 20:20