JavaScript面试之预编译与执行

来源:互联网 发布:翩跹紫晶淘宝 编辑:程序博客网 时间:2024/06/05 00:47

今天面试笔试部分有很多题是考预编译和执行的内容,为了进一步了解,在这写篇博文。

题目

if (a) {         var a = 10;}console.log('a:' + a); // undefined
if (b in window) {         var b = 10;}console.log( b); // 10
function fn() {       console.log('hello');}fn(); // hellovar fn= function() {       console.log('hello world');}fn(); // hello world
var fn = function() {       console.log('hello world');}fn(); // hello worldfunction fn() {       console.log('hello');}hello(); // hello world

以最后一个题目作为例子

  1. 扫描var关键字,提前到最顶端:
    var fn;
  2. 扫描function定义式,提到var之后:
    var fn;
    function fn(){
    console.log('hello');
    }
  3. 顺序执行代码:如下:
    var fn;
    function fn() {
    console.log(‘hello’);
    }
    fn= function(){
    console.log(‘hello world’);
    }
    fn(); // hello world
    fn();// hello world

JavaScript执行顺序

js引擎读取一段js代码,首先预解析,就是逐行读取js代码,寻找全局变量和全局函数,遇到全局变量,把变量的值变为undefind,存在内存中,
遇到全局函数,直接存在内存中,这个过程如果发现语法错误,预解析终止。
我们平时遇到这种情况:
alert(a)
var a=100
这个弹出undefind,而不是没有这个变量的语法错误,就是因为预解析时候把a调成了undefind存在内存中

  • 参考链接
    1. http://www.cnblogs.com/lu607601/articles/js.html
    2. http://www.cnblogs.com/lu607601/articles/js.html