JavaScript and programming beginner - passing functions explanation -
beginner in js, learning book, passing functions example not clear me. code:
function tocentigrade(degfahren) { var degcent = 5 / 9 * (degfahren - 32); document.write(degfahren + " fahrenheit " + degcent + " celsius.<br/>"); } function tofahrenheit(degcent) { var degfahren = 9 / 5 * degcent + 32; document.write(degcent + " celsius " + degfahren + " fahrenheit.<br/>"); } function convert(converter, temperature) { converter(temperature); } convert(tofahrenheit, 23); convert(tocentigrade, 75); <!doctype html> <html lang="en"> <head> <title>chapter 4, example 2</title> </head> <body> </body> </html> i don't understand part function convert. explanation book:
admittedly, use these functions without problem, wouldn’t result in interesting example. instead, third function, convert(), used execute tocentigrade() , tofahrenheit():
function convert(converter, temperature) { return converter(temperature); }this function takes first parameter, converter, , uses function. second parameter, temperature, passed converter() perform conversion , write results document. final 2 lines of code use convert() , pass appropriate converter function , temperature value:
convert(tofahrenheit, 23); convert(tocentigrade, 75);although more complex solution relatively simple problem, demonstrates fact functions values in javascript. can assign them variables , pass them other functions.
what don't understand essence of example - why parameters (converter, temperature), how can assign temperature parameter converter (which function inside function) when temperature not defined - it's word (for me), how after convert function used converting (tofahrenheit, 23 , tocentigrade, 75): example, function tofahrenheit knew should convert function number needed writing conversion result webpage, how? mean, how connected 3 functions in example resulted in printing results webpage? basically, i'm lost of part:
function convert(converter, temperature) { converter(temperature); } convert(tofahrenheit, 23); convert(tocentigrade, 75);
convert(tofahrenheit, 23); passes in tofahrenheit function parameter convert function. therefore:
function convert(converter, temperature) { converter(temperature); } the parameter converter above reference tofahrenheit function. so, in example, code:
converter(temperature); is same as:
tofahrenheit(temperature); i presume author of book trying show functions can passed arguments if required.
Comments
Post a Comment