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 twoalert
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
1 Answer
Reset to default 8Your 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
版权声明:本文标题:javascript - JS Alert showing 'undefined' - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741246870a2365044.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论