When should I use such syntax to define a function in JavaScript
myfunc = myfunc ||
function(n){
return this.length;
};
instead of
myfunc =
function(n){
return this.length;
};
When should I use such syntax to define a function in JavaScript
myfunc = myfunc ||
function(n){
return this.length;
};
instead of
myfunc =
function(n){
return this.length;
};
Basically, when you don't want to override the previous declaration of the function.
For instance, imagine that you have a function A(), which performs a set of actions and it's declared in another library. Maybe you need to use only a small part of it, so you can use the previous syntax to redeclare the function.
It's not a consistent way to program, and it will make the code hard to debug, but it's doable.
In above case this is being checked if myfunc
is not defined, then define that as a function.
So when you are not sure that the myfunc
is already defined you will check if it's undefined
define a function.
As other posters have pointed out, you can use the first expression when you want to define a function which may or may not have been previously defined. It's not a good way to do it though, because the construct does not tell you whether the tested object is a function, and if it is, whether it is the one you're expecting (it could be the result of collapsing libraries).
More generally, the whole redefinition approach should be limited to framework authors, and even with that I'd be quite suspicious of any redefinition, because that would indicate that someone, somewhere, has allowed for either namespace pollution or sloppy dependency management.
I have myself redefined existing functions in some of my past scripts, but these occurrences were all about optimization in a controlled environment, when the initial function determines an execution branch for the current user agent, and redefines itself so that further calls avoid any redundant initialization code.