Javascript: Passing large objects or strings between function considered a bad practice -
is considered bad practice pass around large string or object (lets ajax response) between functions? beneficial in way save response in variable , keep reusing variable?
so in code this:
var response; $.post(url, function(resp){ response = resp; }) function dosomething() { // response here } vs
$.post(url, function(resp){ dosomething(resp); }) function dosomething(resp) { // resp here } assume resp large object or string , can passed around between multiple functions.
objects , strings in javascript passed reference. (technically value of reference, means reassigning = variable inside function won't affect variable outside function, that's besides point question.)
that means not expensive pass them functions because no copy made. passed function pointer original object , efficient.
you need realize first scheme not work properly:
var response; $.post(url, function(resp){ response = resp; }) function dosomething() { // response here } because of timing of things, don't know when call dosomething(). $.post() show asynchronous , have no idea when done. resp value in code must used completion function. must either use in completion function or call completion function , pass resp (like second example). timing correct when data available.
Comments
Post a Comment