by mattmanser · 12y ago · 0 comments
My POV is you simply shouldn't be putting a function in a variable, it's supposed to be reusable code and you've just made it's position a completely pointless dependency as well as obfuscated the code's meaning.
A named function is clearly supposedly immutable, reusable code (save monkey patching). A function in a variable looks like you might change it.
I want to stress, there are very good reasons to assign a function to a variable. There are also very good reasons to declare a function within the scope of another too. But they are few and far between.
To willy nilly declare functions like they're variables. Bizarre. Perhaps someone who does it can explain what it gains them? The place I first saw it was in Crockford's the Good Parts, but he seems to have stopped doing it when you go look at his code.
Would you also object to
var functions = { a: function() {}, b: function() {} }
or var functions = [ function() {}, function() {} ]
?in those cases we're creating a storage structure and loading it with functions - a single variable is just another case of the same.
What about
var log = console.log || function(msg) { };
?The function foo() {} declaration syntax in JavaScript is a syntactic hack that uses function hoisting to allow functions to be used 'before' they are declared. All it does is turn into a var foo = function foo() {} at the top of the current scope.
But because of var scope, variables can also be used before they're declared, so often you don't need it anyway:
var a = function() { return b(); };
var b = function() {};
a();
I suspect people who strongly prefer var foo = function() {} over function foo() {} are people who have internalized the idea of functions as data. I'd hesitate to say 'functional programmers', but perhaps 'functional JavaScripters' is valid.As for "There are also very good reasons to declare a function within the scope of another too. But they are few and far between" - the benefits of closure over parent function scope are incredibly powerful - I don't think they are few and far between at all. I tend to declare pretty much all my functions inside a function using the module pattern:
(function() {
var x = 0;
var f = function() { return x++; };
window.makeObj = function() { return { id: f() }; }
})();In the end, if you think normal function declaration is a "syntactic hack" we're simply not going to agree.
I've used a fair few different languages and to me the distinction between a plain old function and a closure is a useful distinction that helps me read the code quicker.
By declaring it as a variable, you're making it hard to decide which it will be as well.
And deeply coupling code for no good reason. This is the other thing I can't understand. I can't even MOVE your function without worrying about side effects.
On a side note, my original post is going up and down in votes like a yo-yo.
I think the difference here is that you see
function Foo() {
...
}
as a 'normal' function declaration. I see it as a syntax which hides the truth - that that is actually putting var Foo = function Foo() {
..
};
at the top of its scope. It's a special syntax for the special case of "I want this function to have this name and be bound to a variable with the same name for the whole of its enclosing scope". But JavaScript permits me to do lots of OTHER things with functions, and pretending it can't doesn't help me write better JavaScript code.functions are the ONLY way in JavaScript to restrict the scope of a name. How can you talk about the risks of moving things if you aren't even taking advantage of JavaScript's only mechanism to create safely encapsulated name scopes?
I'm talking about simple code structure.
You need a function.
Do you put it in a var or not.
I have nothing against closures or namespaces or object declaration or many of the million other things you can twist objects in js to do.
What I hate is this:
var checkValid = function(item) {
return item!= blah;
}
When it should be: function checkValid(item) {
//blah
}
Stop accusing me of a position you've made up in your head.If it's a pattern you haven't used, I can certainly understand being wary of it at first. But being wary is different than being prescriptive. There is always more to learn.
Binding functions to variables however does highlight the fact that functions are first-class values in JavaScript and can be locally scoped, passed to other functions and can be operated on. Functions in Javascript are not the same as functions C or Java and don't need to pretend to be similar.
If you want to prevent a function binding to be changed, use es6's const and don't pretend that function declarations helps you with that.
projectname = {
A_CONSTANT: ...,
someFunc: function(...) {
},
...
lastFunc: function(...) {
}
}
Basically, JSON layout but with the functions in the resulting namespace.Debugging & diagnostics for this layout in Firefox and Chrome is not a problem. As for IE, well, some things can't be fixed, I guess.
projectname = (function(){
self = {};
self.A_CONSTANT = ...;
self.someFunc = function(...){
};
self.lastFunc = function(...){
};
return self;
})();
I think that produces the exact same end result, but someone set me straight if I'm mistaken.My version is the "static method" version that requires the namespace and a dot before any function calls. I'm OK with that, unless I need a bunch of instances of something.
P.S. - the semicolons don't really do anything (other than make Doug C feel good), as JS is a line oriented language, and will complete statements when they "look done", semis or not. Think of semicolons in JS like colons in BASIC: they let you put a second statement on the same line.
How about simple closures:
function getCounter(){
var num = 0;
return function(){
return num++;
};
}
How about overriding default functions? This is a snippet from a codebase I'm working on right now: require(['helpers/user'], function(User){
// hack because we are not using layout.master
User.isLoggedIn = function(){ return global.userInfo.id > 0; };
});
How about re-using some code in a function? Another snippet from the same code, where self can change based on context: var inCart = function(){
$(self)
.addClass('disabled')
.text('In Cart');
};
if (Cart.isMixIdInCart(results['mixId'])){
inCart();
}else{
$('.widget .purchase').on('click', function(){
$('.widget .purchase').text('Adding');
Cart.addToCart(results['mixId']).done(inCart);
return false;
});
}
These are simply different ways to use closures, but that's part of the benefit of using anonymous functions. function doSomething() {
// do stuff
return this;
}
However, the `return this` line doesn't really have anything to do with the core of what the method is supposed to do. Its largely an implementation detail.I feel the method looks much better like :
var doSomething = fluent(function() {
// doSomething
});
The fluent function handles the `return this;` so it doesn't obscure the core method.It is one of most beautiful aspects of javascript that it enables you to build functions from other functions.
1. Anonymous functions assigned to variables. These make debugging a nightmare. Some (possibly all) versions of IE reports something like "error on line 0" when it occurs in such a function, so you really have no idea what went wrong.
2. Accidental closure creation.
Both of these are avoided by just declaring your functions statically. If you want to create an object, you can still assign a static function to a property, e.g.:
function foo() { ... }
Foo.prototype.foo = foo;
Back when I used to primarily write JavaScript, and compatibility with things like Netscape and IE3 were a concern, I'd write all my code roughly like that and just namespace the functions if they are for a particular class, e.g.: function className_functionName() { ... }
className.prototype.functionName = className_functionName;
This guarantees maximum compatibility with very old versions of JavaScript/JScript, runtime efficiency (functions get evaluated at parse time not runtime, also guaranteeing only one copy of the function code is ever created) and no possibility of accidentally creating a closure where you don't want to (which can lead to memory leaks).The downside is that it it makes your JavaScript code look more like C++ code that Java, and even less like Ruby. It also requires a tiny bit more typing, and we all know how much programmers hate typing.
Don't write JS in that style when compatibility with ancient browsers is not an issue. Hard to read, maintain and understand.
This is my other beef with ignorant javascript programmers, so stuck in the past. Most other languages now do this, and, shock, horror, do it better than js which is horribly behind the times.