开发者

Continuing JavaScript "classes" - enums within

开发者 https://www.devze.com 2023-02-03 03:24 出处:网络
From a previous question, I have the following: So I have implemented a resource class, now I\'d like to c开发者_如何学Continue extending it and add all my constants and enums (or as far as JS will a

From a previous question, I have the following:

So I have implemented a resource class, now I'd like to c开发者_如何学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...


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.


You are missing a comma after tilemap : new c_resource(...) so resources is never properly assigned, so resources.directions.up fails because resources is undefined and undeclared.


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
};
0

精彩评论

暂无评论...
验证码 换一张
取 消