-1

Those 1,2 case are same in using anonymous function in Javascript ?

Normally, case 1 is seen easily.

Case 1 :

$('img:eq(0)').attr('src', ( function(){return '1'} ) ()); //works
console.log((function(){return '1'})()); //works

Case 2 :

$('img:eq(0)').attr('src', function(){return '2'}() ); //works
console.log(function(){return '2'}()); //works

Case 3 : (It seems jQuery parses its function)

$('img:eq(0)').attr('src', function(){return '3'}); //works
console.log(function(){return '3'}); //function

[in Chrome]

Thank you Felix Kling, But

In console,

(function(){alert('1');})() //works

function(){alert('2');}()// SyntaxError: Unexpected token (

Thank you AngularHarsh,

As you can see, there’s a catch. When the parser encounters the function keyword in the global scope or inside a function, it treats it as a function declaration (statement), and not as a function expression, by default. If you don’t explicitly tell the parser to expect an expression, it sees what it thinks to be a function declaration without a name and throws a SyntaxError exception because function declarations require a name.

in your attached link.

fr2lancer
  • 1
  • 2

1 Answers1

0

Not sure what you are asking here. But if see first two functions inside parenthesis they are examples of IIFE. Third is not. For more info, read this: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

Harsh
  • 1,665
  • 1
  • 10
  • 16