DAY 6
2
Software Development

## 變數作用域

• `var`
• `let`
• `const`

``````if(true) {
var myName = 'Ray';
}

console.log(myName); // Ray

function fn () {
var qq = 'Ray';
}
fn();
console.log(qq); // Uncaught ReferenceError: qq is not defined
``````

``````var myName = 'Ray';

if(true) {
var myName = 'qq';
}

console.log(myName); // qq
``````

`let``const` 則是以區塊 (block) 作為區分，什麼是區塊呢？只要你看到 `{``}` 包起來的就是一個區塊、一個 block：

``````if(true) {
let myName = 'Ray';
}

console.log(myName); // Uncaught ReferenceError: myName is not defined
``````

``````if True:
myName = 'Ray'

print('myName:', myName) # myName: Ray
``````

``````def fn():
myName = 'Ray'

fn()

print('myName:', myName) # NameError: name 'myName' is not defined
``````

``````myName = 'Ray'

if True:
myName = 'qq'

print(myName) # qq
``````

## 範圍鍊

``````var myName = 'Ray';

function fn1() {
function fn2() {
function fn3() {
console.log('myName:', myName); // myName: Ray
}
fn3();
}
fn2();
}
fn1();
``````

``````var value = 1; // 全域變數
function fu1() {
console.log(value); // 1
}
function fu2() {
var value = 2; // 區域變數
fu1();
}
fu2();
``````

``````value = 1
def fu1():
print(value) # 1

def fu2():
value = 2
fu1()

fu2()
``````

## nonlocal 與 global

``````def fn1():
def fn2():
def fn3():
``````

``````a = 'Ray'
def fn1():
a = 'AA'
def fn2():
a = 'BB'
def fn3():
a = 'CC'
``````

``````a = 'Ray'
def fn1():
a = 'AA'
print('fn1', a) # AA
def fn2():
a = 'BB'
print('fn2', a) # BB
def fn3():
a = 'CC'
print('fn3', a) # CC
fn3()
fn2()
fn1()
print('global', a) # Ray
``````

``````a = 'Ray'
def fn1():
a = 'AA'
print('fn1', a) # AA
def fn2():
a = 'BB'
print('fn2', a) # BB
def fn3():
global a
a = 'CC'
print('fn3', a) # CC
fn3()
fn2()
fn1()
print('global', a) # 被 fn3 重新賦予導致覆蓋成 CC
``````

``````a = 'Ray'
def fn1():
a = 'AA'
print('fn1', a) # fn1：AA
def fn2():
a = 'BB'
print('fn2 取代前：', a) # fn2 取代前：BB
def fn3():
nonlocal a
a = 'CC'
print('fn3', a)
fn3()
print('fn2 取代前：', a) # 被更改成 CC
fn2()
fn1()
print('global', a) # Global Ray
``````

``````a = 'Ray'
def fn1():
a = 'AA'
print('fn1 取代前：', a) # fn1：AA
def fn2():
def fn3():
nonlocal a
a = 'CC'
print('fn3', a) # CC
fn3()
fn2()
print('fn1 取代後：', a) # fn1：CC
fn1()
print('global', a) # Global Ray
``````

## 關於兔兔們

### 2 則留言

0
zxcv8123123
iT邦新手 5 級 ‧ 2021-09-24 08:08:36

Ray iT邦新手 3 級 ‧ 2021-09-24 08:41:29 檢舉

1
cy186
iT邦新手 5 級 ‧ 2021-11-03 13:13:10

https://realpython.com/python-scope-legb-rule/

Ray iT邦新手 3 級 ‧ 2021-11-04 09:24:08 檢舉