What's the difference in those declarations (in JavaScript)? -


possible duplicate:
javascript: var functionname = function() {} vs function functionname() {}

in javascript can write:

function thefunc(arg) {    ... } 

or

thefunc = function(arg) {    ... } 

or

thefunc : function(arg) {    ... } 

what's real difference , when should use which?

one difference between first , second syntax that's not mentioned (not in linked questions well) if function returns function object results of using 'thefunc' quite different

thefunc = function(arg) {   return function(x) {     return arg+x;   } }(5); res = thefunc(2); // res == 7 

making equivalent to

thefunc = function(5) {   return function(x) {     return 5+x;   } } res = thefunc(2); // res == 7 

because function anonymous. while

function thefunc(arg) {   return function(x) {     return arg+x;   } }  byfive = thefunc(5); res = byfive(2); // res == 7 

would have same result, making function factory reusable.

the practical uses won't clear in these examples, can indispensable, example, in situations complex hook system exists built around callback based calls - such systems plug-ins:

// state object function state(args) {   this.parse = function(data){     data = this.pre_parser(data);      // go on transforming data      return data;   } } state.prototype.pre_parser_factory = function(options){   ... }  var st = new state(args); async_call( function(data, options){               st.pre_parser = st.pre_parser_factory(options);               res = st.parse(data);             }) 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -