javascript耐人寻味    

javascript耐人寻味
   

在思考javascript解释过程的时候,看过别人几篇文章,自己做了几个测试

容易理解,在javascript,形如这样的代码可以正常执行:

alert(hello());
function hello(){
    alert('hello');
}

可以得到“hello”字符串。

形如这样的代码,有问题。

alert(hello());

var hello = function(){

    alert('hello');

}
结果为undefined。两种代码执行结果不同的原因是,在javascript执行之前有个预解释阶段,形如function name()方式定义的函数会优
先赋值,就是说第一遍name变量就已经指向相应函数了,所以第一段代码在解释阶段可以访问到后面的hello函数,第二段代码中,则还要讲到,预解释阶段创建一个活动对象,然后在这个对象里把变量丢进
去,而这种定义函数的方式会然解释器认为hello是一个变量,所以,给他们赋值为undefined,第二段代码实际是以变量的形式保存了hello的值为undefined,故执行阶段时它还是允许了undefined,它在后面才得到函数定义。
当然,html的执行顺序是从上到下执行,那么嵌套在,<script></script>也应该是从上到下一块一块执行,即使是外链接的javascript代
码也不例外。
接下来是这一段代码
function hello(){

    alert('hello');

}

hello();

var hello = function () {

    alert('hello2')

}

hello();

你可以想象上面的解释,然后想象结果。

结果和预想的一样,“hello”,“hello2”。怎么样,是不是有点糊涂了,之前我们把hello放前面,所以执行到前面的hello时是undefined,首先,看上面代码,预解释阶段,本应该报错的第一个hello正常执行,说明
了给hello定义undefined在预解释阶段应该是在函数定义之前
然后是这一段,结果是什么呢,需要思考下了
function hello(){

    alert('hello');

}

hello();

function hello() {

    alert('hello2')

}

hello();

两次都是hello2而不是hello和hello2,结合前面的,可以理解,在预编译阶段已经把hello重新赋值,并且第二次遇见function hello()会忽略,或者说是直接提前了,总而言之,以上代码实际上执行顺序是

function hello(){

    alert('hello');

}



hello = function() {

    alert('hello2')

}
hello();

hello();
就是这样,然后我们在看两段代码,第一段比较简单是这样:
<script type="text/javascript">

    function hello(){

        alert('hello');

    }

    hello();

</script>

<script type="text/javascript">

    function hello() {

        alert('hello2')

    }

    hello();

</script>
得到预想结果,hello 和hello2,不同就是拆成了两块,而代码是一块一块执行的。前面已经提到。
然后下面这一段需要深入仔细的看看,和思考哈哈。
<script type="text/javascript">

    var hello = function () {

        alert('hello');

    }

    hello();

    function hello() {

        alert('hello2')

    }

    hello();

</script>

先不说结果,猜猜是什么结果,是不是有人会以为第二次从新赋值,结果不是和那一段代码一样吗,错了,两次都是hello,是前面的那个函数的值,原因其实很简单function hello()提前了,所以实际上是第一个函数覆盖了第二个函数。

修改了一点东西,同时附上之前看到链接,其实,现在看看,这东西还是有点怪怪,不过它还是挺重要,怎么说,至少要知道其实js解释分两次,有这感觉这对写代码时候是很有帮助:

参考:http://www.jb51.net/article/44123.htm