0

I'm new to objects in javascript and I'm having some problems with the following code.

var Color = function(color){
   this.color = color;
   this.getCode = function(){
      var colorHex;
      var colorRBG;
      switch(color){
          case "White":
              colorHex = "#ffffff";
              colorRGB = "255,255,255";
              break;
          case "Black":
              colorHex = "#000000";
              colorRGB = "0,0,0";
              break;
          default:
              return false;
      }
      return {
          colorHex: colorHex,
          colorRGB: colorRGB
      }
   }
}

What I want to do is get the colorHex value like this but it isn't working:

var newColor = new Color("White");
alert(newColor.getCode().colorHex);

What am I doing wrong?

2
  • 1
    it is working, jsfiddle.net/JQYED/1 in Chrome Commented Apr 5, 2011 at 18:51
  • This is a simplified version of my actual application. Maybe I've another bug somewhere because I keep getting an "undefined" value in my app. Commented Apr 5, 2011 at 18:54

2 Answers 2

1

You need to use this.color instead of color in your switch statement. Color would be undefined here and the default case would be called.

Color (the parameter) is no longer in scope, so you need to access the member variable. Javascript does not automatically prepend this like other languages do, you have to do it manually.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried that but I keep getting "undefined"... I'll post the code below.
Really?? You could try: newColor.getCode.call(newColor) to hack it. Changing switch(color) to switch(this.color) should work though...
I just got it! I was passing a value of "colro" instead of "color" to the function that's why. I didn't see it and this was driving me crazy. BTW, it works fine with just "color" in the switch statement.
1

you need to switch(this.color)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.