查缺补漏

查缺补漏

1. 函数声明提升

function test() {
    foo(); // TypeError "foo is not a function"
    bar(); // "this will run!"
    var foo = function () { // function expression assigned to local variable 'foo'
        alert("this won't run!");
    }
    function bar() { // function declaration, given the name 'bar'
        alert("this will run!");
    }
}
test();

实际上是这样的,

function test() {
    var foo;
    var bar;
    bar = function () { // function declaration, given the name 'bar'
        alert("this will run!");
    }

    foo(); // TypeError "foo is not a function"
    bar(); // "this will run!"

    foo = function () { // function expression assigned to local variable 'foo'
        alert("this won't run!");
    }
}
test();

2. 充分利用 Object.prototype.toString.call();方法,你会发现他是多么强大!

3. 命名函数表达式中的函数名只对内有效,对外是看不见的。

var f = function foo(){
   return typeof foo; // foo是在内部作用域内有效
 };
 // foo在外部用于是不可见的
 typeof foo; // "undefined"
 f(); // "function"

4. 合理使用try catch , 他不会影响代码的正常运行。

    try {
        console.log(a);
    } catch (e){
        console.log(e);
    }
    var b = 10;
    b += 50;
    console.log(b);

5. 注意 DOMContentLoaded和load的区别,前者是针对document而言的, 渲染树生成即触发。 而后者是针对window的,需要所有的资源都下载结束才触发。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>fd.html</title>
</head>
<body>
    <img src="http://u.candou.com/2015/0906/1441528903323.jpg" alt="">
    <img src="http://lovelace-media.imgix.net/uploads/812/3a94d580-7e7a-0133-9f0b-0af7184f89fb.gif?" alt="">
    <div class="dfa"></div>
    <script>
        console.time("time");
        function show(str) {
            console.log(str);
            console.timeEnd("time");
            console.log("
");
        }
        show("1.直接调用show");


        document.addEventListener('DOMContentLoaded',function () {
            show("2.DOMContentLoaded");
        }, false);

        window.addEventListener('load',function () {
            show("3. load");
        }, false);

        show("4. 直接调用show");

    </script>
</body>
</html>

结果如下;

6.

原文地址:https://www.cnblogs.com/zhuzhenwei918/p/6657954.html