I am aware of functions being declared and immediately called, like so
(function(arg) {...}(value))();
but what does this mean:
functionName(function(params){...});
It is in the (first non code line of the) demo/demo.js file of the Ace editor and it is the worst javascript code I have yet encountered. I want to know if it is really poorly written or if I am too novice to decipher it.
In this case,
outerFunc(function(params) { ... })
contains the definition of their module in an anonymous function, which outerFunc uses to control how it's defined. In the code you're referring to they use the define function from RequireJS to do several things, including specifying dependencies and executing context.
define() is part of the CommonJS modules specification, and needs to be implemented differently on different JavaScript platforms you're using. This code design is more than reasonable; it's following the proposed specifications that may be a core part of the language in the future.
An anonymous function is passed to the function functionName().
If it's poorly written, or you are too novice, that depends, because it might be just a legit well usage of this style.
It is not poorly coded. That is an anonymous function being passed to the function functionName. That function will have a name local to functionName and can be called inside it. This can be extremely useful in a lot of cases.
sort(my_arr, function(obj1, obj2){
return obj1.age*obj1.color - obj2.age*obj2.color;
}
);
function sort(arr, compare){
// Sorts arr of objects using compare(arr[i], arr[j]);
}
This would allow you to implement a single sort function sort which works for all possible objects as long as the caller provides a compare function for that type of object.
(function(arg) {...}(value));
This is not a function call. You probably meant (function(params) {...}(value))(someArgs);.
functionName(function(params){...});
This is a call to function functionName, passing that anonymous function in as a parameter.
This is (essentially) the same as:
var f = function(params) { ... };
functionName(f);
or:
function f(params) { ... };
functionName(f);
Consider:
function functionName(f) {
f();
}
That ... now gets invoked.
Related
To improve my understanding of JavaScript, I started to read other people's source code. On Github, I encountered a script that has this variable declaration at the top:
var has = Object.prototype.hasOwnProperty;
Later in the code it's used like this:
if (has.call(params, key)) {
// stuff
}
How does this even work? Effectively, has is now some kind of alias for Object.prototype.hasOwnProperty, but why is it possible to store a prototype method in a variable – since it's now a function call, there isn't anything returned.
A function is a first class citizen in Javascript (as is the case in some other languages as well) that means they can be assigned to variables, passed as arguments to other functions as well as returned from functions. There's a good piece on first class functions on Wikipedia: https://en.wikipedia.org/wiki/First-class_function
You are not storing the function in the variable, you have just created a reference to the function.
Other than tricking existing functions that already implement this as something, why would you want to write a javascript function so that you need to alter its context (via .call or .apply) rather than explicitly passing the "context" as another parameter? Is there a performance benefit?
Example:
function tryIncrement(inc, context) {
context = context || this; // just so we can reuse same fn for the example
if( typeof context.val!= typeof 1|| typeof inc != typeof 1 ) return false;
context.val += inc;
return true;
}
var a = {name: 'A', val: 5}, b = {name: 'B', val: 20};
// reassign internal context
for(var i = 0, n = [1,3,"not a num",5]; i < n.length; i++) {
if( tryIncrement.call(a, n[i]) ) console.log('incremented', i, n[i], a);
else console.log('failed to increment', i, n[i], a);
}
// provide explicit context;
// could just as easily declared function so context was first param
// so it looked the same as previous implementation
for(var i = 0, n = [1,3,"not a num",5]; i < n.length; i++) {
if( tryIncrement(n[i], b) ) console.log('incremented', i, n[i], b);
else console.log('failed to increment', i, n[i], b);
}
There are many cases where you may wish to use this instead of passing an extra parameter. Consider the following function for example:
Function.prototype.async = function () {
setTimeout.bind(null, this, 0).apply(null, arguments);
};
This function allows us to defer a function call as follows:
alert.async("This will display later.");
alert("This will display first.");
You can see the demo here: http://jsfiddle.net/AjwQu/
Instead of binding the function to this we could have passed it as a parameter instead:
function async(funct) {
setTimeout.bind(null, funct, 0).apply(null, [].slice.call(arguments, 1));
}
We would use it like this now:
async(alert, "This will display later.");
alert("This will display first.");
The result is the same: http://jsfiddle.net/63dBF/
However to get the arguments we have to use [].slice.call(arguments, 1) instead. In the first example we could simply use arguments as the function was not a part of the argument list.
Everything has it's advantages and disadvantages. You just need to know what to use when. Hope this helps a bit.
Bonus: It's really easy to convert a function that uses this into a function that accepts an extra parameter and vice versa. First let's define a few utility functions:
var functProto = Function.prototype;
var bind = functProto.bind;
var bindable = bind.bind(bind);
var callable = bindable(functProto.call);
var appliable = bindable(functProto.apply);
The bindable function allows you to create a bindable version of an existing function which when called returns a new function bound to the given arguments.
The callable function allows you to create a callable version of an existing function which when called calls the existing function with the given arguments and this pointer.
The appliable function allows you to create an appliable version of an existing function which when called applies the given arguments and this pointer to the existing function.
Then given the function in the first example we can create the function in the second example as follows:
var async = callable(functProto.async);
See the demo here: http://jsfiddle.net/3dSBS/
Similarly we can convert the function in the second example into the function in the first example as follows:
Function.prototype.async = function () {
return async.apply(null, [this].concat([].slice.call(arguments)));
};
See the demo here: http://jsfiddle.net/rJQyS/
As you can see it's much easier to write a function using this and then construct the function accepting the context as a parameter from it than the other way around.
As far as I can tell the use of this isn't really any different than
another parameter, it just has a more complicated way of being
modified.
I think the easiest way to answer your question is to imagine if the creator of the base Javascript language had followed your conventions.
A world without this
A world without this is a scary noisy place with lots of excessive duplication:
var arr = [1,2,3,4];
arr.reverse(arr); //4321
More opportunities for misleading or verbose syntax
var str = "stringtobesplit";
"abiglongstringnotbeingsplit".split(str,":");
String.prototype.split(str,":");
And its not at all rid of apply at least:
Math.max.apply(arr); //didn't add the initial `this` since it doesn't exist
Effectively there would be a choice between creating only global functions, or creating functions on prototypes or objects that made assumptions about the types of the arguments it was receiving but didn't enforce those assumptions. For instance imagine the toString method in our fantasy world.
You could either create a global toString method which would take in an object of every type ever, and try to make them all work, or you could have a function on the prototypes of each type as it works currently, with no enforcement that it would be called on that type. Someone could call
Array.prototype.toString(str)
And we would need to handle it gracefully (for what its worth doing this with apply seems to revert to the Object.prototype.toString and returns [Object String]). So we would need to identify the correct prototype method to call in those cases, which means my guess is that the convention would be to call
str.toString(str)
or something along those lines.
So whats the point?
this is built to handle the common case for javascript methods on the prototype chain. It gives us a shorthand to allow an object to act on itself without duplicating the call to it or having to know exactly what its prototype is. Without it, we would either have to have no functions on objects, or would have to explicitly call the function on itself every time, introducing extra syntax and potential errors.
call and apply are the exception cases, and apply at least would have uses even if this went away. Its never a good idea to write your apis to the exception cases. If you're creating object oriented code, you should use this as an easy way to refer to the object that is the context for the call. If you write this well, then call and apply should be used rarely and in special situations.
TL;DR - this was designed as part of Javascript for a reason, use it when you're creating methods on objects for more clear and understandable syntax.
When you do object oriented programming your functions WILL depend on the context and it does not make sense do provide it as a parameter, as this would deafeat the purpose of object oriented programming.
It also makes sense to provide an implicit context for callbacks. You do not have to remember the correct order of the parameters if you only need the context. You would not have to use parameters at all in that case. So instead of
function mayCallback(param1, param2, context)
you could just write
function myCallback()
and use this, if you do not need param1 and param2.
To address my main purpose -- is there a performance benefit using this over a function parameter? -- the answer seems to be no:
http://jsperf.com/function-context-vs-parameter
Although there seems to be a slight benefit (may not be significant, however) around using parameter values instead of instance (this) variables within objects.
(Please test for yourself and comment if it's different)
Regarding the purpose being addressed by the other answers: there are some neat use cases as pointed out by #Aadit, maintainability is debatably a personal preference, but like #ben336 said if you're working with Objects (and thus OOP) then this can be more useful.
The ECMAScript 5th-edition native function bind may be an interesting bridge between the two worlds, or at least a time-sucking tangent to explore.
The instance vs parameter values test referenced above may also be a good example of my point -- if you're building a static library of functionality, you can "hijack" obj.callback2 by scoping to a different this, or just call obj.callback directly on your alternate context.
I often come across Javascript code snippets that consist of many anonymous functions that are called where they are created, such as here:
var prealloc = (function() {
// some definitions here
return function prealloc_win(file, size, perms, sparseOk) {
// function body
};
})();
// can be called like this:
prealloc(...);
So this calls an anonymous function which returns another function prealloc_win. To me this seems equivalent to instantiating a class where the resulting object exposes the function prealloc_win:
function preallocObj() {
// some definitions here
this.prealloc_win = function(file, size, perms, sparseOk) {
// function body
};
}
prealloc = new preallocObj();
// can be called like this:
prealloc.prealloc_win(...);
Is this assumption correct? What are the benefits of using anonymous functions that are called directly? And why is this idiom so often seen in Javascript, but not often in other languages which could be written in the same way (C, C++, Python)?
The deal is that the preallocObj class says that this is something that could be
instantiated multiple times. I could just create more instances of it even though it wasn't really designed for that. You could do some hacks to prevent that but it's easier just to use the immediately invoked anonymous function for this.
With the immediately created and invoked anonymous function, a "class" is created, instantly "instantiated" and assigned to prealloc and
there is no way to reference the original anonymous function that created the prealloc object after this. It was created, invoked and lost.
You pretty much have the right idea. The benefits of this module pattern/function builder are that the resultant function can enclose its own internal definitions or state.
It's basically just a way to create a function with private variables or constants. Consider the less efficient alternative:
var prealloc = function() {
// some definitions here
// function body
}
Every time this function is called it would reassign/instantiate its variables, adding unnecessary performance overhead and overwriting any state data that resulted from previous calls.
This method is useful when there are some variables that are important to the workings of a function that you want only private access to or that you need to persist between invocations without contaminating the outer scope.
Javascript is fundamentally very different to C++, JAVA and Python and should be written in differnt ways. At the risk of repetition, Javascript is not an OOP language it is a prototype language. Douglas Crockford (inventor of JSON) at Yahoo has some wonderful articles and particuarily Videos entitled 'Javascript - the good parts' you should watch them all.
I want to know the difference between following javascript functions. Can someone help whats the difference and in what circumstances do we need to use these two functions?
define(function () {
});
the second one is self executing function which is below
(function() { })();
Update
I am using requireJS
Your question title mentions a "jQuery function" but there is no jQuery in the code you've shown.
The first bit of code:
define(function () {
});
...calls a function named define and passes an anonymous function as a parameter (some kind of callback?)
The second:
(function() { })();
Defines an anonymous function and calls it immediately.
"whats the difference and in what circumstances do we need to use these two functions?"
Consult the RequireJS API documentation for guidance on when to use the define() function. As for an immediately-invoked-anonymous-function as in your second example there are many different reasons why you might use such a structure, e.g., a common reason is to create working variables and/or nested functions without creating globals.
To my way of thinking comparing the two (without more context, anyway) doesn't make any more sense than comparing setTimeout(function(){ },1) with (function() { })(); (or comparing any other random function that takes a function as a parameter).
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
Hello all,
I have seen several JavaScript files using this notation:
Start of JavaScript file:
(function() {
// All functions go here.
// Can someone say what the wrapping nameless function is used for?
})();
Also with the prototype library, this seems possible:
function $() {
// Prototype $-wrapping function.
}
Can someone please explain the above two code fragments, their uses and their differences? Some keywords which would help me find more about this notation/technique (how it is named) would be helpful too so I can run a Google search on it... :)
Thanks!
In your first example, people surround their code in an anonymous function for scoping reasons, to avoid global namespace cluttering. That weird parentheses syntax is used to define and execute the function all in one step; the () at the end has the meaning of executing the function itself.
So inside that anonymous function you could define function apple(){} and it would only be accessible inside that anonymous function. This is good if you're making a library and want only certain things to clutter your global namespace.
Your second example is just a simple function called $. Many libraries like to use this name because it's short and concise, and since you need to type it every time you want to reference the libraries namespace, the shorter, the better.
I searched for "javascript wrapping function" and the first hit was this, which says:
This method doesn't add any new symbols to the global or LIB spaces.
I don't understand the second part of the question: function $() { ... } isn't a "nameless" function: it has the name $! If you like functions named $ it's the most straightforward way I know of to make such a thing.
An annonymous function is defined
function() {
}
and then immediately called
()
The extra () enclosing the function is to force the interpreter to treat the function as an expression. Javascript treats any statement starting with the function keyword as a declaration so it could not otherwise be immediatly called.
The purpose is to avoid polluting the global namespace. All variables defined in the function will be local to the function.
Google for module pattern.
retracted in favor of answer to: What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
First one is called immediate function. You can read more about this function pattern here.