从javascript中的对象方法获取变量
我对 javascript 中的对象不熟悉,并且在使用以下代码时遇到一些问题。
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
}
}
}
我想做的是像这样获取 colorHex 值,但它不起作用:
var newColor = new Color("White");
alert(newColor.getCode().colorHex);
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要在 switch 语句中使用
this.color
而不是颜色。此处颜色未定义,并且将调用默认情况。Color(参数)不再在范围内,因此您需要访问成员变量。 Javascript 不会像其他语言那样自动添加此内容,您必须手动执行此操作。
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.
你需要
switch(this.color)
you need to
switch(this.color)