一 叼屠、 作用域
執(zhí)行環(huán)境
執(zhí)行上下文(execution context)瞳腌,也稱執(zhí)行環(huán)境,定義了變量和函數(shù)有權(quán)訪問的數(shù)據(jù)镜雨。環(huán)境中的所有變量和函數(shù)都保存在一個(gè)變量對(duì)象中。當(dāng)某個(gè)執(zhí)行環(huán)境中的代碼執(zhí)行完畢后儿捧,該執(zhí)行環(huán)境被銷毀荚坞,保存在其中的所有變量和函數(shù)定義也隨之銷毀。
全局執(zhí)行環(huán)境是指最外圍的執(zhí)行環(huán)境菲盾,在Web瀏覽器中颓影,就是指window對(duì)象,所有的全局對(duì)象和函數(shù)都是作為window對(duì)象的屬性和方法創(chuàng)建的懒鉴。
每個(gè)函數(shù)都有自己的執(zhí)行環(huán)境诡挂,當(dāng)函數(shù)執(zhí)行完畢時(shí),函數(shù)內(nèi)的變量會(huì)被銷毀临谱。
例如
function printColor(){
var color = "blue";
console.log(color); //blue
}
console.log(color); //報(bào)錯(cuò) "ReferenceError: color is not defined
變量color在函數(shù)printColor中建立璃俗,當(dāng)函數(shù)執(zhí)行完畢時(shí),該函數(shù)的執(zhí)行環(huán)境被銷毀悉默,color這個(gè)變量也被銷毀城豁,因此在全局訪問是訪問不到的。
沒有塊作用域
作用域:顧名思義抄课,就是指變量和函數(shù)的作用范圍唱星;
塊作用域, 塊作用域是指用大括號(hào){}括起來的代碼會(huì)形成一個(gè)作用域,但在JavaScript中是不存在塊作用域的跟磨。
例如间聊,在C語言中:
for(int i = 1; i<5; i++){
printf("%d",i);
}
printf("%d",i);//會(huì)報(bào)錯(cuò)i沒有定義
但在JavaScript中:
for(var i = 1; i<5; i++){
console.log(i);
}
console.log(i);//不會(huì)報(bào)錯(cuò),且會(huì)打印出來 5;
這是因?yàn)樵贑語言中抵拘,大括號(hào){}括住的部分形成了自己的作用域哎榴,在其中聲明的變量i是無法在外部訪問到的。而在javascript當(dāng)中仑濒,沒有塊作用域的概念叹话,在大括號(hào)內(nèi)聲明的變量,在大括號(hào)外也是可以訪問的墩瞳。
思考:這里的 i 在什么域里驼壶?這里會(huì)不會(huì)發(fā)生變量提升?
作用域鏈
在JavaScript中有作用域鏈的概念喉酌,作用域鏈其實(shí)就是執(zhí)行環(huán)境的棧热凹,在標(biāo)識(shí)符解析的過程中泵喘,會(huì)沿著作用域鏈一層一層向上找。
程序在執(zhí)行過程中般妙,沒進(jìn)入一個(gè)新的執(zhí)行環(huán)境就會(huì)將該執(zhí)行環(huán)境壓入執(zhí)行環(huán)境棧中纪铺,每執(zhí)行完畢跳出該執(zhí)行環(huán)境仗哨,就會(huì)將執(zhí)行環(huán)境彈出棧铣鹏。
例如,以下這段程序,程序摘自《Javascript高級(jí)程序設(shè)計(jì)》:
var color = "blue";
function changeColor(){
var anotherColor = "red";
function swapColors() {
var tempColor = anotherColor;
anotherColor = color;
color = tempColor; // 這里可以訪問 color扯键、 anotherColor 和 tempColor
}
// 這里可以訪問 color 和 anotherColor苫拍,但不能訪問 tempColor
swapColors();
}
// 這里只能訪問 color
changeColor();
執(zhí)行環(huán)境的壓棧順序如下:
全局作用域(var color;function changeColor)---->
changeColor()(var anotherColor; function swapColor)---->
swapColor()(var tempColor);
作用域鏈順序如下, 摘自《Javascript高級(jí)程序設(shè)計(jì)》:
作用域鏈從右下角向左上角能訪問的范圍越來越小. swapColor中可以訪問changeColor函數(shù)中的變量芜繁,反之則不可以。
注:自己動(dòng)手試一試 color绒极、 anotherColor 和 tempColor這三個(gè)變量在哪里可以訪問骏令,哪里不可以訪問吧~
面試題
let a = 'global';
function course() {
let b = 'zhaowa';
session();
function session() {
let c = 'session';
teacher();
// 2. 函數(shù)提升
function teacher() {
// 3. 變量提升
// var d = 'yy';
// d = 'yy';
let d = 'yy';
console.log(d);
// 1. 作用域鏈向上查找
console.log('test1', b);
}
}
}
course();
// *************************************
// 4. 提升優(yōu)先級(jí) => 函數(shù)需要變量
// 提升維度:變量?jī)?yōu)先
// 執(zhí)行維度:函數(shù)先打印
// **************************************
// 前置結(jié)論:函數(shù)是天然隔離的方案
// 5. 塊級(jí)作用域
if (true) {
let e = 111;
var f = 222;
console.log(e, f);
}
console.log('f', f);
console.log('e', e);
二 、 閉包
什么是閉包
首先你要知道垄提,閉包沒什么神奇的榔袋,也沒什么可怕的!
閉包是指有權(quán)訪問另一個(gè)函數(shù)作用域中的變量的函數(shù), 創(chuàng)建閉包的常見形式是在一個(gè)函數(shù)內(nèi)部創(chuàng)建并返回另一個(gè)函數(shù)铡俐。
在這個(gè)例子中凰兑,返回的匿名函數(shù)就是一個(gè)閉包。
根據(jù)前面說的執(zhí)行環(huán)境和作用域鏈高蜂,我們知道一個(gè)函數(shù)創(chuàng)建了一個(gè)執(zhí)行上下文聪黎,函數(shù)內(nèi)部的變量在函數(shù)外是訪問不到的,get函數(shù)的a變量在外部是訪問不到的备恤,而閉包的作用就是使我們能夠在函數(shù)外邊訪問到函數(shù)內(nèi)部的變量稿饰,返回的匿名函數(shù)能夠訪問到get函數(shù)的內(nèi)部變量a。
而根據(jù)作用域鏈知道露泊,一個(gè)外層函數(shù)的內(nèi)部函數(shù)是可以向上搜索從而訪問到外層函數(shù)的變量的喉镰,就如同get函數(shù)中的匿名函數(shù)是可以訪問到get函數(shù)中的變量的,因此前者就成為了后者的閉包惭笑。而這種函數(shù)嵌套是我們最常見的閉包形式侣姆。
閉包的作用域鏈
仍以getA()這段代碼為例,當(dāng)函數(shù)get()執(zhí)行完畢時(shí)沉噩,其活動(dòng)對(duì)象不會(huì)被銷毀捺宗,因?yàn)槟涿瘮?shù)的作用域鏈仍在引用這個(gè)活動(dòng)對(duì)象(引用為0時(shí)才可以被銷毀,后面內(nèi)存管理會(huì)說)川蒙。
當(dāng)get()函數(shù)執(zhí)行完畢之后蚜厉,其執(zhí)行環(huán)境的作用域鏈會(huì)被銷毀,但它的活動(dòng)對(duì)象仍然會(huì)留在內(nèi)存中畜眨,直到匿名函數(shù)被銷毀后昼牛,get()函數(shù)的活動(dòng)對(duì)象才會(huì)被銷毀术瓮。因此需要手動(dòng)銷毀來避免內(nèi)存泄漏。
var getA = get();
var res = getA();
getA = null;
由于閉包會(huì)攜帶父函數(shù)的作用域贰健,因此會(huì)比其他函數(shù)占用更多的內(nèi)存胞四,從而影響性能,因此要慎重使用閉包伶椿。
閉包的副作用
作用域鏈的這種機(jī)制導(dǎo)致了閉包保存的是父函數(shù)變量的最終值辜伟。這在出現(xiàn)循環(huán)的時(shí)候就會(huì)產(chǎn)生意想不到的結(jié)果。
function createFunctions(){
var result = new Array();
for (var i=0; i < 10; i++){
result[i] = function(){
return i;
};
}
return result;
}
我們希望這段代碼返回一個(gè)函數(shù)數(shù)組悬垃,其中每個(gè)函數(shù)都能返回對(duì)應(yīng)的索引值游昼,但實(shí)際上由于閉包最終保存的是父函數(shù)最終的變量對(duì)象,此時(shí)的i值為10尝蠕,因此最終返回值都為10。
解決方案如下:
function createFunctions(){
var result = new Array();
for (var i=0; i < 10; i++){
result[i] = (function(num){
return function(){
return num;
};
})(i);
}
return result;
}
在這種解決方案中载庭,調(diào)用每個(gè)匿名函數(shù)的時(shí)候看彼,傳入變量i,由于函數(shù)參數(shù)是按值傳遞的囚聚,所以會(huì)將變量i的當(dāng)前值復(fù)制給參數(shù)num靖榕。而在這個(gè)匿名函數(shù)內(nèi)部,又創(chuàng)建并返回了一個(gè)訪問num的閉包顽铸,這樣一來茁计,result數(shù)組中的每個(gè)函數(shù)都有自己的num變量的一個(gè)副本,因此就可以返回不同的數(shù)值了谓松。
三星压、this 上下文 context
- 我家門前有條河,門前河上有座橋鬼譬,河里有群鴨娜膘。
- 我家門前有條河,'這河上'有座橋优质,‘這河里’有群鴨竣贪。
- this是在執(zhí)行時(shí)動(dòng)態(tài)讀取上下文決定的
考察重點(diǎn) - 各使用態(tài)中的指針指向
函數(shù)直接調(diào)用 - this指向是window
function foo() {
console.log('函數(shù)內(nèi)部this', this);
}
foo()
隱式綁定 - this的指向是調(diào)用堆棧的上一級(jí)
function fn() {
console.log('隱式綁定', this.a)
}
const obj = {
a: 1,
fn
}
obj.fn = fn;
obj.fn();
面試題
const foo = {
bar: 10,
fn: function() {
console.log(this.bar);
console.log(this);
}
}
// 取出
let fn1 = foo.fn;
fn1(); // ??
const o1 = {
text: 'o1',
fn: function() {
// 直接使用上下文 - 傳統(tǒng)分活
// console.log('o1fn_this', this);
return this.text;
}
}
const o2 = {
text: 'o2',
fn: function() {
// 呼叫領(lǐng)導(dǎo)執(zhí)行 - 部門協(xié)作
return o1.fn();
}
}
const o3 = {
text: 'o3',
fn: function() {
// 直接內(nèi)部構(gòu)造 - 公共人
let fn = o1.fn;
return fn();
}
}
console.log('o1fn', o1.fn()); // ?
console.log('o2fn', o2.fn()); // ?
console.log('o3fn', o3.fn()); // ?
- 在執(zhí)行函數(shù)時(shí),函數(shù)背上一級(jí)調(diào)用巩螃,上下文指向上一級(jí)
- 直接變成了公共函數(shù)的話演怎,指向window
如何console.log('o2fn', o2.fn())的結(jié)果是o2
// 1. 顯式人為干涉
fn.call(o2)
// 2. 不許改變this
const o1 = {
text: 'o1',
fn: function() {
return this.text;
}
}
const o2 = {
text: 'o2',
fn: o1.fn
}
// this指向的最后調(diào)用他的對(duì)象,執(zhí)行fn時(shí)避乏,o1.fn搶過來掛載在自己的o2fn上即可
顯式綁定(bind | apply | call)
function foo() {
console.log('函數(shù)this', this);
}
foo();
foo.call({a: 1});
foo.apply({a: 1});
const bindFoo = foo.bind({a: 1});
bindFoo();
追問:call爷耀、apply、bind區(qū)別
- call < = > apply 傳參不同 依次傳入/數(shù)組傳入
- bind 返回值不同
- 面試:手寫apply & bind
// 1. 需求:手寫bind => bind位置 => Function.prototype => 原型
Function.prototype.newBind = function() {
// 2. bind改變?cè)? const _this = this;
const args = Array.prototype.slice.call(arguments);
const newThis = args.shift();
// 核心封裝函數(shù)不執(zhí)行
return function() {
// 執(zhí)行核心apply
return _this.newApply(newThis, args);
}
}
// 2. 內(nèi)層實(shí)現(xiàn)
Function.prototype.newApply = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error');
}
// 參數(shù)兜底
context = context || window;
// 臨時(shí)掛載執(zhí)行函數(shù)
context.fn = this;
let result = arguments[1]
? context.fn(...arguments[1])
: context.fn();
delete context.fn;
return result;
}
new
class Course {
constructor(name) {
this.name = name;
console.log('this', this);
}
test() {
console.log('this1', this);
}
asyncTest() {
// 異步隊(duì)列 => async queue
setTimeout(function() {
console.log('this_async', this);
}, 100)
}
}
const course = new Course('this');
course.test();
course.asyncTest();
思考:如何不寫bind實(shí)現(xiàn)bind效果
es6箭頭函數(shù)
var obj = {
a:1,
func1: function(){
console.log(this.a)
},
func2: () => {
console.log(this.a)
}
}
obj.func1 = obj.func1.bind(obj) // 手動(dòng)指定 func1 的 this 指向
var func1 = obj.func1
func1() // 1
var func2 = obj.func2
func2() // 箭頭函數(shù) this是靜態(tài)綁定淑际,this 指向 window
作業(yè)
- 如下代碼會(huì)報(bào)錯(cuò)嗎畏纲?如果報(bào)錯(cuò)請(qǐng)說明原因扇住,如果不報(bào)錯(cuò)請(qǐng)說明運(yùn)行結(jié)果和原因
for(var i = 1; i<5; i++){
console.log(i);
}
console.log(i);
- 如下代碼輸出是什么?為什么盗胀?請(qǐng)寫出js解釋器實(shí)際執(zhí)行的等效代碼
var v='Hello World';
(function(){
console.log(v);
var v='I love you';
})()
- 如下代碼輸出是什么艘蹋?為什么?請(qǐng)寫出js解釋器實(shí)際執(zhí)行的等效代碼
function main(){
console.log(foo); // ?
var foo = 10;
console.log(foo); // ?
function foo(){
console.log("我來自 foo");
}
console.log(foo); // ?
}
main();
- 如下代碼輸出是什么票灰?為什么女阀?
var a = 10;
var foo = {
a: 20,
bar: function () {
var a = 30;
return this.a;
}
};
console.log(
foo.bar(), // ?
(foo.bar)(), // ?
(foo.bar = foo.bar)(), // ?
(foo.bar, foo.bar)() // ?
);
- 如下代碼輸出是什么?為什么屑迂?請(qǐng)寫出js解釋器實(shí)際執(zhí)行的等效代碼
var a = 10;
function main(){
console.log(a); // ?
var a = 20;
console.log(a); // ?
(function(){
console.log(a); // ?
var a = 30;
console.log(a); // ?
})()
console.log(a); // ?
}
main()
- 為什么點(diǎn)擊所有的button打印出來的都是5而非0,1,2,3,4浸策?要怎么修改?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<ul>
<li><button>0</button></li>
<li><button>1</button></li>
<li><button>2</button></li>
<li><button>3</button></li>
<li><button>4</button></li>
</ul>
</body>
</html>
var buttons = $("button")
for(var i=0;i<buttons.length;i++){
buttons[i].onclick = function(){
console.log(i)
}
}