Javascript --- Immediately - Invoked Function Expression (IIFE) 이 즉시 실행 하 는 함수 표현 식

5012 단어 JavaScript
1. 다음은 몇 가지 형식의 함수 호출 입 니 다.
각종 호출 효율: 이 글 에서 언급 되 었 습 니 다.
http://suqing.iteye.com/blog/1981591
// Either of the following two patterns can be used to immediately invoke

// a function expression, utilizing the function's execution context to

// create "privacy."



(function(){ /* code */ }()); // Crockford recommends this one

(function(){ /* code */ })(); // But this one works just as well



// Because the point of the parens or coercing operators is to disambiguate

// between function expressions and function declarations, they can be

// omitted when the parser already expects an expression (but please see the

// "important note" below).



var i = function(){ return 10; }();

true && function(){ /* code */ }();

0, function(){ /* code */ }();



// If you don't care about the return value, or the possibility of making

// your code slightly harder to read, you can save a byte by just prefixing

// the function with a unary operator.



!function(){ /* code */ }();

~function(){ /* code */ }();

-function(){ /* code */ }();

+function(){ /* code */ }();



// Here's another variation, from @kuvos - I'm not sure of the performance

// implications, if any, of using the `new` keyword, but it works.

// http://twitter.com/kuvos/status/18209252090847232



new function(){ /* code */ }

new function(){ /* code */ }() // Only need parens if passing arguments


 
2.What’s wrong with “Self-executing anonymous function?”
호출 된 함수 표현 식 (IIFE) 이 꼭 익명 은 아니 기 때문에 'Self - executing anonymous function' 이 라 고 불 리 는 JavaScript community members 는 오해 할 만 한 점 이 있다.
// This is a self-executing function. It's a function that executes (or

// invokes) itself, recursively:



function foo() { foo(); }



// This is a self-executing anonymous function. Because it has no

// identifier, it must use the  the `arguments.callee` property (which

// specifies the currently executing function) to execute itself.



var foo = function() { arguments.callee(); };



// This *might* be a self-executing anonymous function, but only while the

// `foo` identifier actually references it. If you were to change `foo` to

// something else, you'd have a "used-to-self-execute" anonymous function.



var foo = function() { foo(); };



// Some people call this a "self-executing anonymous function" even though

// it's not self-executing, because it doesn't invoke itself. It is

// immediately invoked, however.



(function(){ /* code */ }());



// Adding an identifier to a function expression (thus creating a named

// function expression) can be extremely helpful when debugging. Once named,

// however, the function is no longer anonymous.



(function foo(){ /* code */ }());



// IIFEs can also be self-executing, although this is, perhaps, not the most

// useful pattern.



(function(){ arguments.callee(); }());

(function foo(){ foo(); }());



// One last thing to note: this will cause an error in BlackBerry 5, because

// inside a named function expression, that name is undefined. Awesome, huh?



(function foo(){ foo(); }());


3.A final aside: The Module Pattern
javascript 의 모듈 구현 모드 는 함수 가 아 닌 Object 를 되 돌려 줍 니 다.모듈 화 는 관련 방법 과 속성 을 하나의 네 임 스페이스 에 두 고 전체 모듈 의 코드 를 조직 하여 전체적인 변수의 오염 을 낮 추 었 다.
다음은 하나의 예 이다.
 
// Create an anonymous function expression that gets invoked immediately,

// and assign its *return value* to a variable. This approach "cuts out the

// middleman" of the named `makeWhatever` function reference.

// 

// As explained in the above "important note," even though parens are not

// required around this function expression, they should still be used as a

// matter of convention to help clarify that the variable is being set to

// the function's *result* and not the function itself.



var counter = (function(){

  var i = 0;



  return {

    get: function(){

      return i;

    },

    set: function( val ){

      i = val;

    },

    increment: function() {

      return ++i;

    }

  };

}());



// `counter` is an object with properties, which in this case happen to be

// methods.



counter.get(); // 0

counter.set( 3 );

counter.increment(); // 4

counter.increment(); // 5



counter.i; // undefined (`i` is not a property of the returned object)

i; // ReferenceError: i is not defined (it only exists inside the closure)


 
원문 참조: http://benalman.com/news/2010/11/immediately-invoked-function-expression/

좋은 웹페이지 즐겨찾기