开发者

Why does the return value of a function print even though no explicit printing method is called (ex. document.write)?

I just started javascript a few days ago and was playing around with different ways to print the return value of a function.

<script>
function produceMessage(){
    var msg= 'This should print';
    return msg;
}

</script>

<span id="mySpan"></span>

Both these lines of code call methods like write or createTextNode to print the message.

document.body.appendChild(document.createTextNode(produceMessage()));
document.write(produceMessage());

However this line does not call a such a method but the return value is still printing.

document.getElementById('mySpan').innerHTML=produceMessage();

My intuition tells me that in order to have the r开发者_StackOverfloweturn value appear on the screen, you need to call some sort of method that would allow it to be printed, like in this example:

document.getElementById('mySpan').innerHTML=document.write(produceMessage());

However this is incorrect and results in undefined output.


Setting the innerHTML of a element to a string results in the HTML of that element being changed to that string. So,

document.getElementById('mySpan').innerHTML=produceMessage();
  • Calls produceMessage()
  • Sets the innerHTML of element with id mySpan to result

Your function produceMessage returns a string, so the innerHTML of that element is set to This should print.

Your next statement,

document.getElementById('mySpan').innerHTML=document.write(produceMessage());
  • Calls produceMessage()
  • Calls document.write() with the result, which appends This should print to the document
  • Sets the innerHTML of element with id mySpan to the return value of document.write

document.write returns undefined, so the innerHTML of that element is set to the string representation of undefined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜