標籤:fun 情境 沒有 indexof listen list 傳遞 許可權 bsp
範圍和閉包
Q: 1.說一下對變數提升的理解
2.說明this幾種不同的使用情境
3.建立10個<a>
標籤,點擊時彈出對應序號
var i;for(i = 0; i < 10; i++){ (function(i){ var a = document.createElement(‘a‘); a.innerHTML = i + ‘<br>‘; a.addEventListener(‘click‘, function(e){ e.preventDefault(); alert(i); }); document.body.appendChild(a) })(i) }
4.如何理解範圍
5.實際開發中閉包的應用
// 閉包實際應用中主要用於封裝變數,收斂許可權function isFirstLoad() { var _list = []; return function ( id ) { if ( _list.indexOf( id ) >=0 ) { return false; } else { _list.push( id ); return true } } }//使用var firstLoad = isFirstLoad();firstLoad(10); // truefirstLoad(10); // falsefirstLoad(20); // true
(1)、執行內容
範圍:一段<script>或者一個函數
全域:變數定義、函式宣告
函數:變數定義、函式宣告、this、arguments
聲明提前
// 一下寫法不推薦,只是示範聲明提前
console.log(a);//undefinedvar a = 100;fn(‘張三‘);// 張三 20function fn(name){ age = 20, console.log(name,age); var age }
(2)、this
this要在執行師才能確認,定義是無法確認
1 var a = { 2 name:‘A‘, 3 fn:function(){ 4 console.log(this.name); 5 } 6 }; 7 a.fn(); //this===a 8 a.fn.call({name:‘B‘}); //this==={name:‘B‘} 9 var fn1 = a.fn;10 fn1(); //this===Window
this在不同情況下的指代對象不同
a、作為建構函式執行
function Foo (name) { this.name = name; console.log()}var f = new Foo(‘xiaoming‘);f();//
b、作為對象屬性執行
var obj = { name: ‘A‘, printName: function(){ console.log(this.name) } }obj.printName();//this==>obj
c、作為普通函數執行
function fn(){ console.log(this) }fn();//this===>window
d、call、apply、bind
function fn1(name){ alert(name) console.log(this); }fn1.call({x:100},‘小明‘);// 此時this指代的就是 {x:100}
(3)、範圍
JavaScript沒有塊級範圍
if (true) { var name = ‘小明‘; }console.log(name);//小明
函數和全域範圍
// 函數和全域範圍var a = 100;function fn () { var a = 200; console.log(‘fn‘, a); }console.log(‘global‘, a);//100fn();//200
(4)、範圍鏈
// 函數和全域範圍var a = 100;function fn () { var b = 200; // 當前範圍沒有定義的變數,自由變數 console.log( a ); console.log( b )}fn();
var a=100function F1(){ var b=200 function F2(){ var c=300 console.log(a) //a是自由變數,在F2中未找到便向父級範圍F1尋找,仍未找到,繼續向上尋找,在Window中找到 console.log(b) //b是自由變數 console.log(c) } F2()}F1() //100 200 300
調用在當前範圍不存在的變數,便會向父級範圍尋找。需要注意的是,父級範圍是函數定義時產生的,並非函數調用時
(5)、閉包
function F1(){ var a = 100; return function(){ console.log(a);// 自由變數,父範圍尋找 } }var f = F1();var a = 200;f();//100
(1)函數作為傳回值
function F1(){ var a = 100; return function(){ console.log(a);// 自由變數,父範圍尋找 } }var f = F1();
(2)函數作為參數來傳遞
function F2(fn) { var a = 200; fn() }F2(f1)
JavaScript基礎知識——範圍和閉包