`

javascript立即执行函数

 
阅读更多

http://benalman.com/news/2010/11/immediately-invoked-function-expression/

 

// Because this function returns another function that has access to the
// "private" var i, the returned function is, effectively, "privileged."

function makeCounter() {
  // `i` is only accessible inside `makeCounter`.
  var i = 0;

  return function() {
    console.log( ++i );
  };
}

// Note that `counter` and `counter2` each have their own scoped `i`.

var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2

var counter2 = makeCounter();
counter2(); // logs: 1
counter2(); // logs: 2

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

 

Immediately-Invoked Function Expression (IIFE)

Fortunately, the SyntaxError “fix” is simple. The most widely accepted way to tell the parser to expect a function expression is just to wrap in in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

 

// 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

 

 

Saving state with closures

Just like when arguments may be passed when functions are invoked by their named identifier, they may also be passed when immediately invoking a function expression. And because any function defined inside another function can access the outer function’s passed-in arguments and variables (this relationship is known as a closure), an Immediately-Invoked Function Expression can be used to “lock in” values and effectively save state.

 

// This doesn't work like you might think, because the value of `i` never
// gets locked in. Instead, every link, when clicked (well after the loop
// has finished executing), alerts the total number of elements, because
// that's what the value of `i` actually is at that point.

var elems = document.getElementsByTagName( 'a' );

for ( var i = 0; i < elems.length; i++ ) {

  elems[ i ].addEventListener( 'click', function(e){
    e.preventDefault();
    alert( 'I am link #' + i );
  }, 'false' );

}

// This works, because inside the IIFE, the value of `i` is locked in as
// `lockedInIndex`. After the loop has finished executing, even though the
// value of `i` is the total number of elements, inside the IIFE the value
// of `lockedInIndex` is whatever the value passed into it (`i`) was when
// the function expression was invoked, so when a link is clicked, the
// correct value is alerted.

var elems = document.getElementsByTagName( 'a' );

for ( var i = 0; i < elems.length; i++ ) {

  (function( lockedInIndex ){

    elems[ i ].addEventListener( 'click', function(e){
      e.preventDefault();
      alert( 'I am link #' + lockedInIndex );
    }, 'false' );

  })( i );

}

// You could also use an IIFE like this, encompassing (and returning) only
// the click handler function, and not the entire `addEventListener`
// assignment. Either way, while both examples lock in the value using an
// IIFE, I find the previous example to be more readable.

var elems = document.getElementsByTagName( 'a' );

for ( var i = 0; i < elems.length; i++ ) {

  elems[ i ].addEventListener( 'click', (function( lockedInIndex ){
    return function(e){
      e.preventDefault();
      alert( 'I am link #' + lockedInIndex );
    };
  })( i ), 'false' );

}

 

 

 

 

分享到:
评论

相关推荐

    JavaScript中立即执行函数实例详解

    ( function(){…} )()和( function (){…} () )是两种javascript立即执行函数的常见写法,最初我以为是一个括号包裹匿名函数,再在后面加个括号调用函数,最后达到函数定义后立即执行的目的,后来发现加括号的原因...

    深入解析JavaScript中的立即执行函数

    立即执行函数模式在JavaScript中可以让你的函数在定义后立即被执行,下面我们就来深入解析JavaScript中的立即执行函数,需要的朋友可以参考下

    JavaScript立即执行函数的三种不同写法

    主要介绍了JavaScript立即执行函数的三种不同写法,需要的朋友可以参考下

    详解javascript立即执行函数表达式IIFE

    本文主要介绍了javascript立即执行函数表达式IIFE的相关知识。具有很好的参考价值,下面跟着小编一起来看下吧

    深入浅析javascript立即执行函数

    在Javascript中,任何function在执行的时候都会创建一个执行上下文,因为为function声明的变量和function有可能只在该function内部,这个上下文,在调用function的时候,提供了一种简单的方式来创建自由变量或私有子...

    深入理解javascript中的立即执行函数(function(){…})()

    ( function(){…} )()和( function (){…} () )是两种javascript立即执行函数的常见写法,最初我以为是一个括号包裹匿名函数,再在后面加个括号调用函数,最后达到函数定义后立即执行的目的,后来发现加括号的原因...

    深化解析JavaScript中的立刻执行函数_.docx

    深化解析JavaScript中的立刻执行函数_.docx

    【JavaScript源代码】JavaScript函数this指向问题详解.docx

     一、 函数内 this 的指向 1、普通函数2、构造函数3、对象方法4、事件绑定方法5、定时器函数6、立即执行函数 1、普通函数 2、构造函数 3、对象方法 4、事件绑定方法 5、定时器函数 6、立即执行函数 二、...

    js中的立即执行函数1

    IIFE(立即调用函数表达式)IIFE( 立即调用函数表达式)是一个在定义时就会立即执行的 JavaScript 函数。示例当函数变成立即执行的函数表达式时,

    JavaScript闭包和立即执行函数的个人笔记

    闭包和立即执行函数一、闭包二、闭包的作用三、闭包形式四、立即执行函数五、使用环境六、小练习 一、闭包 当a函数已经执行完了,b函数才开始。 原创文章 10获赞 3访问量 453 关注 私信 展开阅读全文 作者:...

    JavaScript中的立即执行函数表达式介绍

    主要介绍了JavaScript中的立即执行函数表达式介绍,本文着重讲解了什么是立即调用函数表达式,需要的朋友可以参考下

    JavaScript自执行函数和jQuery扩展方法详解

    自执行函数是用一对圆括号将匿名函数包起来,加括号(传参)会立即执行。因为函数无名字,实现了作用域的绝对隔离和函数名的冲突问题。基本形式如下: (function () { console.log('do something'); })();

    深入理解JavaScript系列

    深入理解JavaScript系列(4):立即调用的函数表达式 深入理解JavaScript系列(5):强大的原型和原型链 深入理解JavaScript系列(6):S.O.L.I.D五大原则之单一职责SRP 深入理解JavaScript系列(7):S.O.L.I.D...

    JS立即执行函数功能与用法分析

    本文实例讲述了JS立即执行函数功能与用法。分享给大家供大家参考,具体如下: 相信大家经常会遇到下面这两种写法: (function(){ ... })() 和 (function(){ ... }()) 关于这样写是什么意思呢?有什么区别呢? 在...

Global site tag (gtag.js) - Google Analytics