Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于ReferenceError #6

Open
tjuking opened this issue Sep 28, 2015 · 0 comments
Open

关于ReferenceError #6

tjuking opened this issue Sep 28, 2015 · 0 comments

Comments

@tjuking
Copy link
Owner

tjuking commented Sep 28, 2015

定义

ReferenceError表示的是引用了不存在的对象(查看MDN文档说明

触发场景

一般情况下,引用一个变量之前,我们会先声明这个变量。下面这段代码就不会抛出ReferenceError。

var me;
//...
if(me){
    //...
}

或者:

if(me){
    //...
}
var me;//声明会提前

如果变量没有声明,引用变量则ReferenceError就会被抛出。如下面这段代码:

if(me){
    //...
}

或者:

(function(){
    var me;//闭包环境中
    //...
})();
if(me){
    //...
}

注意事项

在判断全局变量是否存在时,需要注意不能使用直接引用判断这种方式:

console && console.log("支持console");//在不支持console的浏览器中会报错

应该去检查console变量是否挂在window对象下:

window.console && console.log("支持console");

或者:

"console" in window && console.log("支持console");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant