論js閉包的重要性

來源:互聯網
上載者:User

標籤:

很久沒寫部落格了,今天發現了一個很有意思的問題,寫下來分享一下

話不多說,貼前端代碼:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script> <script type="text/javascript">     $(function(){         $("#btnky").bind(‘click‘,function(){              //發送給服務端              var postMoney=getMoney();              alert("發送給後台:"+postMoney);              $.post("to_json.html",{postMoney:postMoney},function(data){                  alert(data);              });         });     })     function getMoney(){             return 1;     } </script> </head> <body> <input type="button" value="發送後台" id="btnky"> </body>

 前端一個很簡單的ajax提交代碼,對不對?通過getMoney()函數 得到一個值,然後發送給後台,注意,該函數是不包含在$()代碼塊裡面的

 後台代碼:

 也是很簡單的,只是響應使用者的發送資料,代碼如下:

1 2 3 4 5 6 @RequestMapping("/to_json.html") @ResponseBody public String to_Json(@RequestParam("postMoney") int postMoney){     System.out.println("前端發送的錢:"+postMoney);     return "你給服務端發送的money是:"+postMoney; }

OK,萬事具備,頁面走起!!

頁面點擊發送

看後台:

 

貌似沒錯,後台如願得到我們要的資料

只是,如果有些搗蛋鬼喜歡搗蛋呢?比如我用Firefox的firefox注入一個getMoney()方法

好吧,我注入了一個和頁面上相同的函數getMoney(),居然返回100000.太壞了..

OK,讓我們在點擊發送後台按鈕,看看是什麼情況呢?

天呐.......居然真給變了...

好吧,再看看我們的服務端,是不是也會隨波逐流呢?

我已經無語了,這別個搗蛋鬼豈不是能隨便傳送資料...

不然,如果頁面修改一下呢?代碼如下:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <script type="text/javascript">     $(function(){         $("#btnky").bind(‘click‘,function(){              //發送給服務端              var postMoney=getMoney();              alert("發送給後台:"+postMoney);              $.post("to_json.html",{postMoney:postMoney},function(data){                  alert(data);              });         });         function getMoney(){             return 1;         }     })       </script> </head> <body> <input type="button" value="發送後台" id="btnky"> </body>

 

注意,這次我的getMoney()函數寫在$()這個裡面去了

OK,我們在重新整理頁面,做相同的操作,注入一個getMoney

很奇怪呢,居然沒有變化,不放心,再看看後台:

也沒有變化,是不是很有意思呢?

論js閉包的重要性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.