What is the difference between anonymous and inline functions in JavaScript? [closed]

The title sums up my question. An example that demonstrates the point would be nice.

Answers:

Answer

First off, there doesn't seem to be a consensus definition for inline functions in JavaScript. I consider an inline function to be a special case of a JavaScript function. An inline function is a function assigned to a variable that is created at runtime instead of at parsetime.

Anonymous functions and inline functions are practically the same, in that they are created at runtime. The difference is that an inline function is assigned to a variable and so it can be reused. In that way, inline functions work the same as a regular function.

Function

function func() {
    alert ('function');
} 

$('a').click(func);

Inline Function

var func = function() { 
    alert ('inline') 
};

$('a').click(func);

Anonymous Function

$('a').click(function() {
    alert('anonymous');
});

Anonymous and inline functions can have performance penalties versus a regular function. See var functionName = function() {} vs function functionName() {}.

Answer

Inline function is somewhat different , quoting from wikipedia :

an inline function is a function upon which the compiler has been requested to perform inline expansion. In other words, the programmer has requested that the compiler insert the complete body of the function in every place that the function is called, rather than generating code to call the function in the one place it is defined. Compilers are not obligated to respect this request.

Javascript does not support the concept of inline function. But i found some references in web where callbacks like:

(function(){
  setTimeout(/*inline function*/function(){ /*some code here*/ }, 5);})
();

are called inline function. As you can see these function do not have any name either , so they are essentially same as anonymous function. I think ,since you are defining the function where you are using it ,it's been referenced by inline function but the name "anonymous function" best describes the notion.

Answer

Anonymous functions are defined like this

var x = 1;
(function(x){
    // Do something
    console.log(x); // 1
})(x);

However, the definition of inline function is a bit unclear to me.

Answer

Inline function

var foo = function (){ 
   alert('Hello') 
}
setTimeout(foo, 100);

Anonymous function

setTimeout(function(){ 
   alert('Hello') 
}, 100);

They are doing the same thing, but inline function is better when you want to reuse it. Anonymous is good for one-time use because you do not need to worry if its name will conflict with other variables, and it's shorter.

So it depends on your situation.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.