js匿名函數和閉包的學習

來源:互聯網
上載者:User

匿名函數的寫法總結有三種:

//函數字面量:首先聲明一個函數對象,然後執行它。(function(){    alert(1);})();//優先運算式:由於Javascript執行運算式是從圓括弧裡面到外面,所以可以用圓括弧強制執行聲明的函數。(function(){    alert(2);}());//Void操作符:用void操作符去執行一個沒有用圓括弧包圍的一個單獨運算元。void function(){    alert(3);}();

 

<input type="text" id="txtUser" name="txtUser" value="ok" /><a href="javascript:tests();">調用匿名函數</a>

 

function tests(){    var temps = document.getElementById("txtUser");    alert(temps);    //匿名函數,調用方法,把上面的txtUser的文字框對象,用匿名函數去執行。這樣控制了把它定義成全域變數。    (function(temps){        alert(temps.value);    })(temps);}

下面做個例子,通過閉包、執行匿名函數,返回一個對象。

//執行一個匿名函數,返回一個對象,把對象賦值給Test。var Test = (function(cTest){   var a = 1;  //在這裡定義的變數,比如a、b、c、d,在整個Test下都可以訪問到   var b = 2;   var c = cTest;   var d;    return{        getA:function(){            return a;        },        getB:function(){            return b;        },        getC:function(){        return c;        }    }})(3);
function testss(){    alert(Test.a);//不能得到a的值:是個undefined    alert(Test.c);//不能得到c的值:是個undefined    alert(Test.getA());//結果得到a的值:1    alert(Test.getB());//結果得到b的值:2    alert(Test.getC());//結果得到c的值:3}
<a href="javascript:testss();">閉包</a>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.