Execution Context
Syntax Parser
Execution Context
Lexical Environment
name / value pair
object
// name / value
address: '64 Yen Do'
// object
address: {
street: 'Yen Do',
number: 64,
district: {
name: 'Binh Thanh',
ward: 17
}
}
global environment & global object
global environment: là execution environment (global) đầu tiên mà JS khởi chạy
global = “not inside a function”
var a = 'hello'
function b() {}
a thuộc gloval var
a cũng thuộc global object
truy cập a bằng nhiều cách
a
window.a
this.a
called b
hello world
Called b
undefined
# undefined = var a (I've not set value for a)
# uncaught errror = no a (there is no a at all in the code)
Execution Context bao gồm 2 phase:
Javascript is single-threaded and synchronous
thứ tự các function:
variable environment
# global context
myVar = 1
# a() context
myVar = 2
# b() context
myVar = undefined
# back to global context
myVar = 1
the scope chain
# vì outer environment của b() là global chứ không phải a()
myVar = 1
# b() lúc này đã nằm trong execution context của a(), nên outer environment của b() là a()
myVar = 2
myVar = 2
uncaught error: b is not defined
# bởi vì chưa từng có hàm b() được setup ở global environment
# không có myVar trong scope của a() lẫn b(), nên JS sẽ tiếp tục tìm bên ngoài nữa, là global
myVar = 1
what about asynchronous & callback?
# kết quả console.log
finished function (still wait 3s)
finished execution
click event!
# nghĩa là click handler chỉ thực thi SAU khi các JS chính đã chạy xong
