bigcheez Posted April 27, 2010 Share Posted April 27, 2010 I am writing a function that is getting somewhat sizable.There are a few lines of code that get repeated.If I were to turn these lines into a function, they would be of no use elsewhere.I figured a subfunction would be perfect for the situation.I checked a coupled references and tried googling for javascript subfunctions.Are subfunctions in javascript ... non-existent?frowned upon?undocumented?deprecated?etc ... Link to comment Share on other sites More sharing options...
ShadowMage Posted April 27, 2010 Share Posted April 27, 2010 Don't know much about this type of thing but a little testing indicates that this does indeed work. Not sure if it works in all browsers as I only tested it in FF and IE. function testAlert() { function funcInFunc(msg) { alert(msg); } funcInFunc("This is a function in a function");} Link to comment Share on other sites More sharing options...
Synook Posted April 27, 2010 Share Posted April 27, 2010 There is no such thing as a "subfunction", in most languages, and it is definitely not a standard construct. You are probably thinking of lambda functions. You could think of jkloth's code more: function testAlert() { var funcInFunc = function(msg) { alert(msg); } funcInFunc("This is a function in a function");} And it is clear that funcInFunc is created as a lambda function (of sorts) with its scope restricted to inside testAlert.Note that if you instead wrote: function testAlert() { this.funcInFunc = function(msg) { alert(msg); }} You would be creating a method of (the now object) testAlert, which would also serve your purposes. Link to comment Share on other sites More sharing options...
jeffman Posted April 27, 2010 Share Posted April 27, 2010 Note: there are several good reasons for creating a "private" function. One, it makes sure that the private function always takes precedence over a global function that happens to have the same name. Two, it makes sure the private function can never be called from a different scope.Both these reasons are mostly applicable when you are writing a code library, for yourself or someone else. We often forget what our libraries contain, and this makes sure we don't goof up, and that our "customers" don't goof up.(There are other reasons, too.)In most situations, it actually makes more sense to write the "private" function as a global function -- the very thing you are worried about here. Short, single-purpose functions make code more readable, debuggable, and maintainable. Some shops limit function lengths to something like 15-20 lines. As a rule, that's probably unworkable. But it's not a bad guideline at all. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.