SlightlyLoony
Tera Contributor
Options
- Subscribe to RSS Feed
- Mark as New
- Mark as Read
- Bookmark
- Subscribe
- Printer Friendly Page
- Report Inappropriate Content
‎02-09-2010
07:34 AM
Here's a simple and very useful feature of JavaScript that you may not be aware of: functions may be nested, one inside another. Here's a simple example, in a script you can run on your instance:
<div>
gs.log('Hex value of 11259375 is: ' + hex(11259375));
function hex(value) {
var rem = value;
var result = '';
while (rem > 0) {
var r = rem % 16;
rem = Math.floor(rem/16);
result = hexChar(r) + result;
}
return result;
function hexChar(charValue) {
return '0123456789ABCDEF'.charAt(charValue & 0xFF);
}
}</div>
Note that the function hexChar is entirely within the function hex.
You might say: "Ok, but why on earth would I ever want to do this?" Fair question. There are at least two good reasons that I can think of: (1) you have some code that will be used repeatedly in the outer function, and which isn't useful outside that function, and (2) you can break up a large function into smaller, easier to understand (and maintain) pieces.
- 536 Views
1 Comment
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.