admin管理员组

文章数量:1279182

Hi there,

I just moved from C#/C++ to JavaScript last night, and am loving it!

I've just e across some behavior that I don't understand, wondering if anyone can shed some light on it?

When I call this script, I'm getting the expected alert box showing '5.5', however after that box is closed I get another alert simply showing "undefined", can anyone shed any light on this?

Code below:

var myObj = {

age : 5,
weight : 5.5,

toString : function(){
    alert(this.weight);
}

}

alert(myObj.toString());

Many thanks

Hi there,

I just moved from C#/C++ to JavaScript last night, and am loving it!

I've just e across some behavior that I don't understand, wondering if anyone can shed some light on it?

When I call this script, I'm getting the expected alert box showing '5.5', however after that box is closed I get another alert simply showing "undefined", can anyone shed any light on this?

Code below:

var myObj = {

age : 5,
weight : 5.5,

toString : function(){
    alert(this.weight);
}

}

alert(myObj.toString());

Many thanks

Share Improve this question asked Oct 11, 2013 at 11:55 Lee BrindleyLee Brindley 6,5126 gold badges43 silver badges65 bronze badges 2
  • 3 The fact that you have two alert() functions in your code might be a hint as to why you get two alert boxes ;) – Niet the Dark Absol Commented Oct 11, 2013 at 11:57
  • The question wasn't why do I have two alerts... It was why is the second showing undefined, which has been answered now. Many thanks – Lee Brindley Commented Oct 11, 2013 at 11:59
Add a ment  | 

1 Answer 1

Reset to default 8

Your code calls alert() twice.

The first alert is the one displaying this.weight. But then the second displays whatever value is returned from the myObj.toString() function, and since you've coded that function without an explicit return value it returns undefined by default.

Normally a .toString() function would actually return a string, so you should do this:

toString : function(){
    return this.weight.toString();
}

Then you'll just get the one alert, as shown here: http://jsfiddle/eph7x/

And indeed then you can simply use:

alert(myObj);

...because your custom .toString() will get called automatically.

本文标签: javascriptJS Alert showing 39undefined39Stack Overflow