為什么報pi未定義的錯誤呢?
? ? function parent(){
? ? ? ? var pi = Math.PI;
? ? ? ? child();
? ? }
? ? function child(){
? ? ? ? console.log(pi);
? ? }
? ? parent();
? ? function parent(){
? ? ? ? var pi = Math.PI;
? ? ? ? child();
? ? }
? ? function child(){
? ? ? ? console.log(pi);
? ? }
? ? parent();
2016-11-17
舉報
2019-05-06
javascript的作用域問題,可以看看?https://github.com/mqyqingfeng/Blog/issues/3
按你的理解輸出 1, 其實是11111111
2017-03-19
這是js變量作用域鏈的問題, 或者丟在glob作用域中 window.pi = Math.PI;
window
+-- parent
????+-- pi
+-- child
child與parent同級, 但pi在parent里面.
就好像你能看到鄰居的房門, 但永遠不知道里面的裝飾是怎樣的,?
除非他把鑰匙給你 : child(pi)
或者把鑰匙放在門邊: window.parent = function(){}; window.pi=Math.PI;
2016-11-18
pi變量未在child的函數(shù)作用域鏈中,應在child的函數(shù)中聲明pi變量,或者將child函數(shù)丟到parent函數(shù)中,如:
function parent(){
? ? ? ? var pi = Math.PI;
? ? ? ?function child(){
? ? ? ? alert(pi);
? ? ? ?}
? child();
? ? }
? ? parent();