Skip to content

Instantly share code, notes, and snippets.

@GeekaholicLin
Last active September 3, 2016 08:28
Show Gist options
  • Select an option

  • Save GeekaholicLin/d0377e67124836f17cc2b85dc124c539 to your computer and use it in GitHub Desktop.

Select an option

Save GeekaholicLin/d0377e67124836f17cc2b85dc124c539 to your computer and use it in GitHub Desktop.
javascript 易错点

this 易错点

Foo.method = function() {
    function test() {
        // this 将会被设置为全局对象(译者注:浏览器环境中也就是 window 对象)
    }
    test();
}
//因为test()被当成一般函数进行处理,挂载到window/global全局下

setTimeout循环易错点

for(var i = 0; i < 10; i++) {
    setTimeout(function() {
        console.log(i);  
    }, 1000);
}

//改为===>

for(var i = 0; i < 10; i++) {
    (function(e) {
        setTimeout(function() {
            console.log(e);  
        }, 1000);
    })(i);
}

//或者改为===>

for(var i = 0; i < 10; i++) {
    setTimeout((function(e) {
        return function() {
            console.log(e);
        }
    })(i), 1000)
}

Array 构造函数易错点

new Array(3, 4, 5); // 结果: [3, 4, 5]

new Array(3) // 结果: [],此数组长度为 3

由于只有一个参数传递到构造函数中(译者注:指的是 new Array(3); 这种调用方式),并且这个参数是数字,构造函数会返回一个 length 属性被设置为此参数的空数组。 需要特别注意的是,此时只有 length 属性被设置,真正的数组并没有生成。应该尽量避免使用数组构造函数创建新数组。推荐使用数组的字面语法。它们更加短小和简洁,因此增加了代码的可读性。

参考链接

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment