JS中 “is not defined” 我今天找了一些资料和自己试验了各种方法,都不能得到正解,故写了这个问题的解决方案。
首先什么是is not defined?
从字面意思上来讲就是未定义,也就是未申明。就是这个变量(对象)压根就没有。如下:console.log(sojson);//sojson is not defined
可能还一知半解,我们继续往下看。
is not defined 和 undefined 区别。var so;
console.log(so);//undefined
console.log(so.a);//so.a is undefined
这个时候输出的是undefined。访问变量的属性就会提示is undefined就是这个变量so未定义值(类型);
而defined呢,如下:console.log(so);//so is not defined
其实如果理解一下其实就是未申明。也就是可以理解变量的过程是,先声明后赋值,在赋值的过程中确定了这个变量的类型。
所以总结一下:is not defined 优先于 undefined ,也就是先判断这个对象是否申明了,如果没申明直接就 is not defined,如果已经申明,那么再看有没有赋值(类型),如果没有那么就是 undefined 或者 访问对象的属性就是 is undefined 。
is not defined 如何避免
比如我们常用的jquery,如果出现了jQuery is not defined ,或者$ is not defined ,那么我们按以下步骤来排查:是否引入了jQuery(注意是否404)。
jQuery是否在依赖jQuery的js之前引用(因为js加载是自上而下加载)。
是否过多引入jQuery,或者引入多个版本的jQuery。
我们自己定义对象的时候,对外要提供方法,如下://申明局部变量 so。
var so = {
a : function(){};
}
//对外提供访问。
window.so = so;
如何判断 undefined。
undefined 很好判断,如下:var sojson;
console.log(sojson == undefined);//true
console.log(sojson === undefined);//true;
console.log(typeof sojson == 'undefined');//true
console.log(typeof sojson === 'undefined');//true
console.log(!sojson);//true
//... ...
如何判断is not defined
我在网上没找到合适的资料来判断“is not defined”,我项目中因为是公共js需要解决,对象是否定义。都不好判断。所以我用比较low的方式来判断的,如果你有好的点子,请留言或者告知我,我加上。try{
var x = sojson.demo;
}catch(e){
console.log(e.message);//sojson is undefined
}
因为抛出了Exception,所以能catch,进入了catch模块。如果有多个,请分开cache,如下:try{
var x = sojson.demo;
}catch(e){
console.log(e.message);//sojson is undefined
}
try{
var y = sojson.y;
}catch(e){
console.log(e.message);//sojson is undefined
}
因为出现一个Exception,就不会往下执行了,所以要分开去处理。
如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。
¥我需要走的更远,点击我 赞助。
如果还有疑问,点击我加群,为你提供最好的解答。