chuanxshi / javascript-patterns

JavaScript Design Patterns

Home Page:http://shichuan.github.io/javascript-patterns

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

function-declarations and recursive

boris-42 opened this issue · comments

// named function expression
/* Benefits:
* 1. Provides the debugger with an explicit function name: helps stack inspection.
* 2. Allows recursive functions: getData can call itself.
* Issues:
* 1. there are historic quirks with IE
*/
var getData = function getData () {
};

This is very bad idea. We have already possibility for recursion in previous both examples.

While all functions (absolutly annonimus also) can call itself using arguments.callee.

For Example:

var some = function(a){
if(a == 0 || a == 1)
return 1;

var t = arguments.callee; 
return  t(a-1) + t(a-2);  

}
alert(some(5));

I believe in strict mode, arguments.callee is no longer going to be available, precisely because functions should be named. As I understood it, this was a bad idea for security reasons, and is being pushed back.

On the same note of function declarations... I'm think we should consider a naming pattern when you are adding a function as a property within another object. Consider this code:

var api = {};
api.someFunction = function apiSomeFunction("?") {
  //do I recurse with api.someFunction() or apiSomeFunction()?
  //Both work, which raises the question, is there ever a scenario a which api.someFunction
    *won't be defined at the point it gets called*?
};

Lastly, I think we should establish the naming convention above, where functions as properties of other objects are camelCased from obj.subFunction to either subFunction or, objSubFunction