简体   繁体   中英

Continuing JavaScript “classes” - enums within

From a previous question , I have the following:

So I have implemented a resource class, now I'd like to continue extending it and add all my constants and enums (or as far as JS will allow...).

This is what I currently have:

var resources = {
  // images
  player  : new c_resource("res/player.png"),
  enemies : new c_resource("res/enemies.png"),
  tilemap : new c_resource("res/tilemap.png")
};

And this is what I would like to continue to extend it to:

var resources = {
  // images
  player  : new c_resource("res/player.png"),
  enemies : new c_resource("res/enemies.png"),
  tilemap : new c_resource("res/tilemap.png"),

  // enums
  directions : {up:0, right:1, down:2, left:3},
  speeds     : {slow: 1, medium: 3, fast: 5}
};

...

function enemies() {
  this.dir = resources.directions.down; // initialize to down
}

When I attempt to access resources.directions.up, my JS script goes down in a flaming pile of burning code. Are enums allowed in this context, and if not, how can I properly insert them to be used outside of a normal function? I have also tried defining them as global to a similar effect.


edits: fixed the comma...that was just an error in transcribing it.

When I run it in Firefox and watch the console, I get an error that says resources is undefined .

The resources 'class' is defined at the top of my script, and function enemies() directly follows...so from what I understand it should still be in scope...

tilemap : new c_resource(...)之后,您缺少逗号tilemap : new c_resource(...)因此resources从未得到正确分配,因此resources.directions.up失败,因为resources未定义和未声明。

It works: http://jsfiddle.net/XfurM/2/

In JavaScript, enums can be achieved by simply declaring an array or object, using the literal notation:

var weekdays = [
    'Monday',
    'Tuesday', 
    'Wednesday', 
    'Thursday', 
    'Friday', 
    'Saturday', 
    'Sunday'
];  

or

var weekdays = {
    Monday: 1,
    Tuesday: 2,
    Wednesday: 3,
    Thursday: 4,
    Friday: 5,
    Saturday: 6,
    Sunday: 7
};

What's the call stack to enemies ? You could have done something like this:

var foo = {
  bar: 1,
  f_rv: f()
};

function f() {
  return foo.bar;
}

which works halfway since you can declare functions "below" the code that uses them, but fails later since f() attempts to use foo , which is not constructed at the moment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM