2-14 function invocation and the execution stack

bigword alert : invocation

  • running a function
  • in js, using parenthesis ()

圖解 execution stack

  • 每次function被執行,都會建立新的 execution context,即使是呼叫自己

  • stack 最上層的context正在被執行


2-15 functions, context adn variables

bigword alert : variable environment

  • where the variables live

bigword alert : scope

  • where a variable is available in your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

function b(){
var myvar;
console.log(myvar);
}

function a(){
var myvar = 2;
console.log(myvar);
b();
}

var myvar = 1;
console.log(myvar);
a();
console.log(myvar);


/*
1
2
undefined
1
*/

try to draw a picture below


2-16 Scope Chain

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

function b(){
console.log(myvar);
}

function a(){
var myvar = 2;
b();
}

var myvar = 1;
a();


/*
1
why?
*/

Ans

  • 如果var 不在該execution context,js engine 會到outer environment 找

  • outer environment is depend on where the function sits lecically(set up in creation phase)

  • note : 不是到stack下一層找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19



function a(){
function b(){
console.log(myvar);
}

var myvar = 2;
b();
}

var myvar = 1;
a();


/*
2
*/


2-17 scope ES6 and let

(Recall) bigword alert :scpoe

  • where a variable is available in your code

let

  • block scoping
  • not allow to use the variable (access undefined) until the line ofcode is run