简体   繁体   中英

JS Alert showing 'undefined'

Hi there,

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

I've just come 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

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.net/eph7x/

And indeed then you can simply use:

alert(myObj);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM