Use IIFE and ES6 Let
Question Add five Button - Use IIFE Closer ES6
首先介紹IIFE
- Immediately Invoked Function Expresstion 立即執行函數
- 擁有獨立的執行環境,避免變數名稱的衝突,在創建完成就執行
- IIFE Exsample
var $ = "Jquery Used"; (function(n){ var $ = "My number is: "; function getNumber(n){ return console.log($+n); } getNumber(n); })(1)
-
結合閉包,擁有存變數的能力Exsample Show
(function createButton(){ for(var i=1;i<=5;i++){ var button = document.createElement('Button'); var body = document.getElementsByTagName('body')[0]; button.innerHTML = 'Button '+ i; (function(num){ button.onclick = function(){ alert('This is Button: ' + num); } })(i); body.appendChild(button); } })()
-
拆分函數
(function createButton(){ for(var i=1;i<=5;i++){ var button = document.createElement('Button'); var body = document.getElementsByTagName('body')[0]; button.innerHTML = 'Button '+ i; addClickFunctionality(button, i); body.appendChild(button); } })() function addClickFunctionality(button, num){ button.onclick = function(){ alert('This is Button: ' + num); } }
-
使用ES6的Let
(function createButton(){ // 把var改成let就實現了Block Scoped for(let i=1;i<=5;i++){ var button = document.createElement('Button'); var body = document.getElementsByTagName('body')[0]; button.innerHTML = 'Button '+ i; button.onclick = function(){ alert('This is Button: ' + i ); } body.appendChild(button); } })()
Published 23 Jun 2017