js預編譯原理
阿新 • • 發佈:2018-11-11
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js預編譯原理</title> </head> <body> <script type="text/javascript"> // var a = 0.1 , b = 0.2; // if(a + b == 0.1){ // document.write('√'); // }else{ // document.write('×'); // } 註釋內容可自行操作一下看看結果,這裡lz告訴你結果是× test(); function test() { document.writeln('有輸出'); } //結果是可以輸出 document.write(a); var a = 123; //結果輸出的是undefined </script> <!--3.125e7--> </body> </html>
可見javascript的預編譯過程遵循2個要素:
1.函式宣告整體提升
2.變數 宣告提升
<!DOCTYPE html> <html> <head> <title>js預編譯處理</title> <meta charset="utf-8"> </head> <body> <script type="text/javascript"> function fn(a) { console.log(a); var a = 123; console.log(a); function a () {} console.log(a); var b = function () {} console.log(b); function d () {} } fn(1); //預編譯過程: // 1.首先建立一個AO物件( Action Object ) ( 執行期上下文 ) // 2.檢視函式體形參和變數宣告,將其作為AO屬性名並賦值為undefined // 3.實參和形參統一 // 4.在函式體裡找函式宣告,值賦予函式體 // AO { // 1. a : undefined, // b : undefined, // 2. a : 1, // b : undefined; // 3. a : function a () {}, // b : undefined, // d : function d () {} // } // 所以列印結果: 123 function a() {} function b() {} 123 </script> </body> </html>
以為這就完了?學懂讓你懷疑以前函式白學了。
<!DOCTYPE html> <html> <head> <title>預編譯處理2</title> <meta charset="utf-8"> </head> <body> <script type="text/javascript"> //上述預編譯處理是在函式內部,而全域性預編譯處理大同小異,全域性預編譯會先生成一個GO物件,這裡G0 === Window,舉個小例子: var c = 123; function c() {} console.log(c); //整體先預編譯後才有內部編譯,因此AO物件會覆蓋GO物件 function test() { var a = b = 234; console.log(); console.log(window.b); //未經宣告唄賦值的變數歸全域性物件所有,結果234 console.log(window.a); //a是AO物件而非全域性物件,結果為undefined } test(); </script> </body> </html>
<script type="text/javascript">
//弄懂了再看這個例子
global = 100;
function fn () {
console.log(global);
global = 200;
console.log(global);
var global = 300;
console.log(window.global);
}
fn();
var global;
//結果: undefined 200 undefined //lz看了一晚上才弄懂,比較攪,各位想搞懂可以去找資料詳看
//分析:
// 首先建立 GO {
// global : 100,
// }
// 執行fn()
// 然後 AO {
// global : undefined,
// global : 200,
// global : 300, window.global : 100;
// }
// GO {
// x : undefined,
// z : 234,
//}
function fx() {
console.log(y); //AO執行完,undefined
if(x) {
var y = 100;
}
console.log(y); //x無值,undefined
z = 234;
console.log(z); //AO無此變數,上GO要,234
}
var x;
AO {
y : undefined,
}
fx();
x = 10;
console.log(z); //全域性,234
</script>