Get variable from object method in javascript
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;
开发者_StackOverflow中文版 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?
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.
you need to switch(this.color)
精彩评论