PDA

View Full Version : Calling A Function



locbtran
09-27-2011, 02:02 AM
I would like to call a function within a function. Is this even possible??
When I do this I get "undefined"

Here's my code:

<html>
<head>
<script type="text/javascript">
function product(a,b){
total = a*b;
display(total);
}

function display(num){
return num;
}
</script>
</head>

<body>
<h1>This text I do NOT want to be erased.</h1>

<a href="http://google.com" target="_blank">Total: </a>
<script type="text/javascript">
product(3,4);
document.write(display());
</script>

</body>
</html>

I know you can just return in the first function, "product()" but I would like to do something else in my second function "display()" then return a value.

thanks

jscheuer1
09-27-2011, 02:31 AM
I take issue with much of what's going on here. But to demonstrate the answer with as little modification of the original code as possible:


<html>
<head>
<script type="text/javascript">
function product(a,b){
var total = a*b;
return display(total);
}

function display(num){
return '<span style="color: red;">' + num + '<\/span>';
}
</script>
</head>

<body>
<h1>This text I do NOT want to be erased.</h1>

<a href="http://google.com" target="_blank">Total: </a>
<script type="text/javascript">
document.write(product(3,4));
</script>

</body>
</html>

As you can see, display() is being run from product, adding the red span wrapper to the mathematical result.

As a side note, call is technically a different procedure. It's a process whereby the this keyword (if used) of a called function is predefined or set while optionally passing it other arguments:


<html>
<head>
<script type="text/javascript">
function product(a,b){
var total = a*b;
return display.call(total, 'red');
}

function display(color){
return '<span style="color: ' + color + ';">' + this + '<\/span>';
}
</script>
</head>

<body>
<h1>This text I do NOT want to be erased.</h1>

<a href="http://google.com" target="_blank">Total: </a>
<script type="text/javascript">
document.write(product(3,4));
</script>

</body>
</html>