This question already has answers here:
var functionName = function() {} vs function functionName() {}
(41 answers)
Closed last year.
What's the difference between these two ways of declaring a function?
function someFunc() { ... }
var someFunc = function() { ... }
I'm not asking in the technical sense. I'm not asking which is better for readability, or which style is preferred.
I am on different opinion with most of the people here. Technically this syntax may mean the same for declaring functions both ways
(I stand incorrect on my last statement. I read up on a diff post why they are technically diff and I'll add in the end, why)
; but the way they play a role in evolving patterns is massive. I would highly recommend "Javascript: The Good Parts" by Doughlas Crockford.
But to prove my point in a subtle and a simple manner; here is a small example.
//Global function existing to serve everyone
function swearOutLoud(swearWord) {
alert("You "+ swearWord);
}
//global functions' territory ends here
//here is mr. spongebob. He is very passionate about his objects; but he's a bit rude.
var spongeBob = {
name : "squarePants",
swear : function(swearWord) {
name = "spongy";
alert("You "+ swearWord);
return this;
}
}
//finally spongebob learns good manners too. EVOLUTION!
spongeBob.apologize = function() {
alert("Hey " + this.name + ", I'm sorry man!");
return this;
}
//Ask spongebob to swear and then apologize in one go (CASCADING EFFECT!!)
alert(spongeBob.swear("twit").apologize());
if you look at the code above I declared a function with a name swearOutLoud. Which would take a swear word from any object or a call and will give you the output. It can do operations on any object using the "this" parameter that is passed to it and the arguments.
However second declaration is declared as an attribute of object called "spongeBob". This is important to note; as here I am moving towards an object driven behavior. While I am also maintaining "cascading effect" as I return "this" if i have nothing else to return.
Somthing similar is done in jquery; and this cascading pattern is important if you are trying to write a framework or something. You'll link it to Builder design pattern also.
But with functions declared as an attributes of an object I am able to achieve an object centric behavior which leads to a better programming paradigm. Unless designed well; individual functions declared outside with global access lead to a non-object oriented way of coding. I somehow prefer the latter.
To see cascading in effect, look at the last statement where you can ask spongebob to swear and apologize at once; even though apologize was added as an attribute later on.
I hope I make my point clear. The difference from a technical perspective may be small; but from design and code evolution perspective it's huge and makes a world of a difference.
But thats just me! Take it or leave it. :)
EDIT:
So both the calls are technically different; because a named declaration is tied to global namespace and is defined at parse time. So can be called even before the function is declared.
//success
swearOutLoud("Damn");
function swearOutLoud(swearWord) {
alert("You " + swearWord)
}
Above code will work properly. But code below will not.
swear("Damn!");
var swear = function(swearWord) {
console.log(swearWord);
}
One advantage of using function someFunc() { ... } is that the function name appears in Firebug debugger. Functions that are declared the other way (var someFunc = function() { ... }) come up as anonymous.
Actually, the difference is that the second declaration gives us the ability to declare functions like this making it possible to have a function as a property for an object :
var myObject=new Object();
myObject.someFunc=function() { ... };
Style wise the second example is more consistent with other common ways to declare functions and therefore it could be argued that it is more readable
this.someFunc = function() { ... }
...
someFunc: function() { ... },
However, as also mentioned it's anonymous and therefore the name does not appear when profiling.
Another way to declare the function is as follows which gets you the best of both worlds
var someFunc = function someFunc() { ... }
Another difference is that, on most browsers, the latter allows you to define different implementations depending on circumstances, while the former won't. Say you wanted cross-browser event subscription. If you tried to define a addEventListenerTo function thusly:
if (document.addEventListener) {
function addEventListenerTo(target, event, listener) {
....
}
} else if (document.attachEvent) {
function addEventListenerTo(target, event, listener) {
....
}
} else {
function addEventListenerTo(target, event, listener) {
....
}
}
on some browsers, all the functions end up being parsed, with the last one taking precedence. Result: the above just doesn't work. Assigning anonymous functions to variables, however, will work. You can also apply functional and basic aspect oriented programming techniques using anonymous functions assigned to variables.
var fib = memoize(function (n) {
if (n < 0) return 0;
if (n < 2) return 1;
return fib(n-1) + fib(n-2);
});
...
// patch the $ library function
if (...) {
$ = around($, fixArg, fixResult);
}
It is both true that the first form:
function test() { }
is a more recognized syntax and that the second form:
var test = function() { ... }
allows you to control the scope of the function (through the use of var; without it, it would be global anyway).
And you can even do both:
var test = function test() { ... test(); ... }
This allows you to define a recursive function in the second form.
For readability, I'd say the first is clearly better. A future maintenance programmer, even assuming they're familiar enough with javascript to know many of the finer points coming up in this thread, are going to assume the first format.
For example, if they should some day want to ctrl-f to search for the definition of your function to see what's happening in there, are they going to first search for someFunc = function() or function someFunc()?
Also, to get downright typographical about it (since we're talking readablity) readers are often scanning the text quickly, and would be more inclined to skip over a line that starts with "var" if they're looking for a function definition.
I know this is a non-technical answer, but it's harder for humans to read code than computers.
When you write
function Test() {
}
JavaScript is really creating a property to which it assigns the function object that once called will execute the code reported in the function definition. The property is attached to the object window, or to the object that contains the function definition.
Related
In Introduction to Object-Oriented JavaScript, a formal description is given on how to use javascript in an object oriented fashion. Your code for functions inside objects would like along the lines of:
$(function() {
var oPerson = new cPerson("Florian");
alert("Hi! My name is " + oPerson.sMyNameIs());
});
function cPerson(sSetName)
{
var sName= sSetName;
var oPersonInst = this;
this.sMyNameIs = function () {
return sName;
};
}
With a bit more experience, you probably want a more clearcut reference to the instantiated class, so you modify the class code as such (and I add another function too):
function cPerson(sSetName)
{
var sName= sSetName;
var oPersonInst = this;
this.sMyNameIs = function () {
return oPersonInst.sName;
};
this.sMyFullNameIs = function () {
return oPersonInst.sMyNameIs();
};
}
Now we have come accross three different ways of referring to function or variables from within class functions:
return sName;
return this.sName;
return oPersonInst.sName;
Suppose I want to call the sName variable in the instantiated class very specifically, and these example functions will get more and more and even more complex and in depth as development goes on.
I think that the first option ('return sName;') is uncertain, as you are not quite sure whether you are referring to the variable in the right targeted instantiated class scope. It could be an accidental local var that you are calling.
The second, using this, IMHO, is also not perfect as this apparently changes depending on situations, and you can't (?) rely on that you are calling the right variable in the instantiated class specifically.
So the third reference, is IMHO, the best looking reference. Very specifically defined right at instantiation of the class. How can there be any doubt that the var sName of the class is meant.
Q1: Why are functions in the class defined with this.? Can it not better be defined with oPersonInst.something = function () { //... }; ?
Q2: why does, in code that I have given, alert(oPersonInst.sMyNameIs()); work, but alert(oPersonInst.sName); does not (at least, not within $.each( something, function() { //right here }) ), but alert(sName); DOES work (not favored IMHO, because of the above mentioned reasons)?
Q3: Can someone pot some exemplary code, or maybe even change this sample code, where solid out-of-local-scope references are used, that will work outside as well as inside $.each(...) callback functions (or other callback related functions) ?
Forgive my confusion, we're all learners, and I feel a hole in my brain. This article did not explain my concerns over this very well.
this doesn't change randomly at all.. it always means the current closure (function):
if you are in function_1() -- this means function_1
if you are in function_1>function_2 -- function_2 is the current closure and this means function_2
IF you need function_1's this in function_2 you have to capture it while in function_1: meaning var function1This = this;
and the way to reference a var by using the functions name before it means static access. It has different semantics
so use this.var to be sure you get the INSTANCE's variable
use a 'captured this pointer' to access your parents INSTANCE's variable
and only use name.var if you want to get the static, shared (between all instances) value
When a function that calls one or more other functions, and these functions being called are only ever used by the one calling function, how should the code be structure?
For example if you have funcB() and funcC() which are only ever called by funcA() should funcB() and funcC() be anonymous functions or nested functions or if they are part of a class should they simply be declared private or placed in inner class?
I'm currently working with JavaScript but have encountered the same situation while using other languages such as C++ and Java.
According to Wikipedia JavaScript does have nested functions though I've never seen it used?
When I'm starting a project, I tend to avoid encapsulating functionality until things are getting stable.
As Dancrumb pointed out, function calls aren't free, so you might need some minor refactoring down the line. But when you're looking at code you haven't touched in months, that nice clean organization will be good for your mental health. And that's exponentially more true when you're working in a team :)
If funcB() and funcC() do not conceptually make sense alongside funcA() then you should not make the public.
Traditional OOP would say you should make them private.
It's my opinion that nearly always there is another concept to which funcB() and funcC() belong. You should make them public methods on different class. Whatever holds funcA() holds a private instance of that class.
It's difficult to make a compelling case for this while talking abstractly about A, B and C. But I would say if they do not conceptually belong with funcA() then there is something else that they do conceptually belong to. If you agree with that premise and agree that composition is better than inheritance, the conclusion is to make them public on some other class.
There are a number of approaches here.
Javascript supports anonymous functions that can be defined and assigned to a variable anywhere in your code.
Thus, you could write:
function foo() {
var bar = function() { /* some code */ };
bar();
}
And bar would not be available anywhere else. This might be useful for encapsulating functionality, but I don't think it's a very scalable model for development.
There's a school of thought that suggests that any function that is called only once could, in the future, be something worth calling more than once. In this case, you can create functions that are 'private':
var Foo = (function() {
var Foo = function() {
/* some constructor code */
};
var private = function() { /* a private function */ };
Foo.prototype.public = function() {
private();
/* And some other stuff */
};
return Foo;
})();
var foo = new Foo();
foo.public(); /* Includes a call to the private method */
In this, your private method is truly private, so you don't have to expose inner workings to the world.
But really, that's more of a discussion of how to implement access modification. There's plenty of information out there to answer that question. The bigger, design question is whether to implement separate functions, or whether to just inline them.
My choice is generally to tuck cohesive pieces of function into... well, into functions. The cost of a function call is non-zero, but worry about that after the fact... if you identify that the function call is a performance bottleneck, then you can worry about whether you're calling too much and whether you should refactor your code to use fewer calls.
Until that time, write your functions, call them and revel in clear code. Just make sure you use good method names :)
If funcB and funcC are created as a closure inside your class and you don't 'expose' these to the interface, then they can change (be removed, added, return different values, etc...) without worrying about how they've been implemented outside the Class.
Once they are exposed all bets are off and they might need to be unit tested, supported, etc. This is a well known rule.
A closure is simply a function declared within the scope where its going to be used.
Method A
function MyClass(){
function funcA(i){
funcB(i);
funcC(i);
}
function funcB(i){
//...
}
function funcC(i){
//...
}
return {funcA:funcA}
}
va mc = new MyClass()
for(var i = 0;i<100000;i++){
mc.funcA(i);
}
Method B:
function MyClass(){
function funcA(){
function funcB(){
}
function funcC(){
}
for(var i = 0;i<100000;i++){
funcB();
funcC();
}
// funcB, funcC are created before and then released after this
}
return {funcA:funcA}
}
va mc = new MyClass()
mc.funcA();
Method B might be less preferred when funcA is called many times because assignment is optimally expensive.
Method B might be preferred when considering memory. Although it's debatable since funcA and funcB are resident in both MyClass and MyClass.funcA.
In JavaScript and other languages, I've heard about Activation Objects being created as you invoke a method / function. In order to optimize and maintain a good performance, it sounds like a developer should limit how many functions are being called.
Now if there's no way around it and you must call multiple methods, is it better to call one method after another, like this:
myFunc1();
myFunc2();
myFunc3();
// or...
var myFuncs = [myFunc1, myFunc2, myFunc3];
for(var a=0, aLen=myFuncs.length; a<aLen; a++) {
myFuncs[a]();
}
OR, to nest them like this:
function myFunc1() {
// Do something...
myFunc2();
}
function myFunc2() {
// Do Something else...
myFunc3();
}
function myFunc3() {
//Do one last thing.
}
//Start the execution of all 3 methods:
myFunc1();
I'm assuming it makes more sense to go with the 1st technique, since it comes back to the previous scope and releases the last Activation Object... but if someone could confirm this,
I would really like to know!
Thanks
In order to optimize and maintain a good performance, it sounds like a developer should limit how many functions are being called.
Yes and no. Functions (or more generally, subroutines) are there to be called, and not doing so makes no sense. If you can make your code more DRY by introducing another function, do so.
The only place where not using them is reasonable are high-performance loops which run thousands of times doing little work, and function calls would add a noticable overhead. Do not try to prematurely optimize!
Also, there are some languages which handle recursion not well and where you will need to translate recursive function calls to loops, preventing stackoverflow exceptions. However, this is a rare case as well.
is it better to call one method after another, or to nest them?
That depends, since the two techniques do different things. With #1, there are just 3 independent functions which are called after each other. In contrast, #2 defines functions that always call each other - you can't get myFunc2 without myFunc3. Is that intended?
If it is, there's nothing wrong with this nesting. The two additional stack layers will not harm your performance.
For information concerning Activation Objects, please refer to http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/#more-546
This is not an optimization level concern however, as the concern you listed is an example of EXTREME pre-optimization and your time is not worth that type of investment. And actually, the example you listed above, there is little to no savings when you are looking at Activation Objects alone.
As for proper use however, I try to encapsulate as much as I can. If a function doesn't have to go in the global scope, and can live within the scope of another function, then that's where it should be declared.
for example, for better scoping.
var f2 = function() {
}
var f1 = function() {
f2()
}
// is not as nice as:
var f1 = function() {
var f2 = function()
f2()
}
// or even better..
var f1 = function() {
function() {
}() ; execute
}
Separation of responsibility:
private function myFunc1(): void
{
}
private function myFunc2(): void
{
}
private function myFunc3(): void
{
}
private function doAllFunc(): void
{
myFunc1();
myFunc2();
myFunc3();
}
I saw this pattern:
Money = (function() {
function Money(rawString) {
this.cents = this.parseCents(rawString);
}
});
in this CoffeeScript screencast preview. (The homepage for the screencast is here.)
Now, I don't understand this pattern. There is a Money function that contains a Money function. What's that about?
Could someone explain?
As quoted, there's no point to that pattern other than that the outer Money symbol can be deleted from the window object (except on IE7 and below, but that's another story) because it's a normal (implicit) property of window (as opposed to a var or a symbol deriving from a function declaration). But even then, the outer Money symbol receives a function that does absolutely nothing. Could it be misquoted?
For instance, here's a fairly standard patttern:
Money = (function() {
var someCompletelyPrivateVariable;
function doSomethingCompletelyPrivate() {
}
function Money(rawString) {
this.cents = this.parseCents(rawString);
}
return Money;
})();
That's the module pattern, and it lets you have completely private variables and functions (both illustrated) whilst only having one public symbol. But I've had to edit a fair bit to create that (the most significant edits being the return Money; at the end and the addition of () after the anonymous function so we're calling it rather than just defining it.
Using the CoffeeScript code that the video claims is a proper conversion...
class Money
constructor: (rawString) ->
#cents = #parseCents rawString
...CoffeeScript will generate the following, which is basically identical to #T.J. Crowder's answer:
var Money;
Money = (function() {
function Money(rawString) {
this.cents = this.parseCents(rawString);
}
return Money;
})();
I'm just posting this to show what CoffeeScript actually does, and that the video does not represent the reality.
You can see the conversion if you visit the site and click the "Try CoffeeScript" button.
Please do not "accept" this answer.
EDIT:
To add some private variable usage that utilizes the scope, you could do this:
class Money
priv=0
constructor: (rawString) ->
#cents = #parseCents rawString
#id = priv++
...which renders as:
var Money;
Money = (function() {
var priv;
priv = 0;
function Money(rawString) {
this.cents = this.parseCents(rawString);
this.id = priv++;
}
return Money;
})();
By the way, I know nothing about CoffeeScript. Its syntax looks confusing to me, but perhaps just because I'm not accustomed to it.
I like JavaScript the way it is (especially with the new and yet to come changes).
I'm the author of the screencast mentioned, and the source of the snippet. A few clarifications:
The context in which the snippet was mentioned was in an animated comparison of JavaScript and CoffeeScript syntax.
It was intentionally simplified so as to not add extra confusion in the context of the CoffeeScript concept being taught at that exact moment in the video (the video was not trying to teach JavaScript constructor or class syntax).
You can get the full JavaScript text of any CoffeeScript snippet by running it through the CoffeeScript compiler as shown in the screencast, or by running it on the official CoffeeScript website.
I'll add a clarification to the video and preview mentioned above.
Otherwise, the other explanations here on Stack Overflow are correct. If you're building a JavaScript class you should return the current object and call the anonymous function shown above. But that's not the point of CoffeeScript. ;-)
It doesn't look like a real example, the grouping operator of the "outer" function is pointless and as TJ says, it does absolutely nothing. Called as a constructor, it will return an empty object.
#TJ - the quote is correct, you need to watch about 40 seconds of the video.
Money = (function() {
var uid = 0;
function Money(rawString) {
this.cents = this.parseCents(rawString);
this.uid = uid++;
}
return Money;
})();
Another use case of this pattern is to have local variables that act as if there statically bound to the function.
This is subtly different from the module pattern because your adding static private information to a function. Instead of packaging data and returning an object which has some local variables in scope.
The other option for achieving this would be using Money.uid but that would be public.
There are three things going on here:
First, as other answerers have noted, the code given in the PeepCode screencast and cited in the question has a couple of mistakes. There is a return, and the outer function is called.
Second, as T.J. noted, this is a module pattern. You can execute arbitrary code in CoffeeScript class blocks, and variables obey the same scoping rules as in other functions. So, for instance, you could write
class HashedPassword
salt = Math.random()
constructor: (password) ->
#value = hash password, salt
in which case salt is visible only within the HashedPassword class definition.
Finally, it should be noted that this is the only place that CoffeeScript ever uses "named" functions (those declared with function foo() rather than foo = function()). Named functions are great for stack traces and such, but they cause inconsistencies between IE (< 9) and other browsers unless scoped in a module like this (see the CoffeeScript FAQ, heading "Is there any way to name functions, for reflection and recursion?"). So a secondary use of the class syntax is to safely declare named functions.
I hope that answers your question, Šime.
The outer Money function takes no arguments. The inner Money function captures rawString via closure. The advantage here is that you're not polluting the global namespace with the inner Money function definition.
EDIT: I would agree with TJ that the pattern as it stands is useless. It doesn't do anything and the outer function is used solely for scoping. Without seeing the screencast author's complete example, it's hard to tell where he is going with this.
What is the 'best practise' with regard to coding style.
Should I use _ for private members?
Should I use this._privateMember?
Please re-write my code in proper style if its wrong:
(function()){
var _blah = 1;
someFunction = function() {
alert(_blah);
};
someOtherFunction = function {
someFunction();
}
}();
I would read this and incorporate any part you agree with:
http://javascript.crockford.com/code.html
You do not have to agree with all of it
I don't think there is one. Use a prefix if you think it helps.
I use _ for private members because it distinguishes them which can be quite helpful in Javascript when you have variables coming from all over the place. But they do clutter the code a bit.
I don't use _ for variables that are declared using var. I do however, use _ to denote object members that shouldn't be access directly.
Some people (who are strange in my opinion :P), also prefix variables with a $ if it contains a jQuery object.
As long as you are consistent with what you do, there are no problems.
Aside from just the code you're showing now, you should use Capital Letters to distinguish constructor functions, and camelCase to name instances of objects.
function Foo (val) {
this.set(val);
};
Foo.prototype.get = function () {
return this._dontTouchMePlease;
};
Foo.prototype.set = function(val) {
this._dontTouchMePlease = parseInt(val, 10);
};
var aFoo = new Foo(6);
I think that its generally accepted that if a variable name starts with a _, you probably shouldn't touch it (accept in dire cirumcstances and even then, two keys and special codes should be provided).
If I'm remembering my Crockford correctly, you'll want to put var in front of the two inner functions, otherwise they will be implicit globals. If you want them to be globals, then that's moot. Either way, your second inner function declaration should probably end in a semicolon. This might be a misformating thing, but I think its generally accepted that the bodies of functions are indented one more level in. Also, I've never seen the (function()){/* stuff */}(); construction before, but that says pretty much nothing.
I'd write it these ways - one for if your just declaring a function and another for if your using an anonymous function and immediately applying it to get a result, because I don't which one you're trying to do (again, if you want the inner functions to be global, then this won't be what you intended):
//function declaration
var myFunction = function () {
var _blah = 1;
var someFunction () {
alert(_blah); //or console.log(_blah); for debugging purposes
};
var someOtherFunction () {
someFunction();
};
};
//using a one-of to assign a result
/* NOTE: if you are using this version, myResult will be undefined
(at least given the functions you provided), but like I said,
I don't recognize the construction you provided, and am therefore
assuming that you meant one of these two, which could be a perfectly
falacious assumption, and in that case, my apologies
*/
var myResult = function () {
var _blah = 1;
var someFunction () {
alert(_blah);
};
var someOtherFunction () {
someFunction();
};
}();
BTW, (and I don't want to overstep) Crockford's "JavaScript: The Good Parts" is a stellar reference for JavaScript syntax. He also has, on his website a JavaScript style guide of sorts (though I don't know how widely followed it is). Link is: http://javascript.crockford.com/code.html
I also use the "_" in c# for private/protected members. It is a fast way to see if the variable is a member-variable or not. And you can access it faster with code-completion because you don't get in mess with the public members (private: _blah , public property: Blah).
But are there any private members in javascript anyway? I think every variable defined as member is accessible from the outside.
So you don't have a public wrapper for the private member. And that means the "_" is a bit a overhead and the same can be achieved with "this.".
I prefer you to use the following stuffs which is preferably used around the world programmers.. see below
i = Int
f = Float
o = Object
r = Return
a = Array
e = Element
g = Global declaration
hook = a function which can be used for hooking with other functions
call = a function which can be used for making call from client to server system
sync = a function which can be used for SYNC
and so on.. you can prefix on your coding...