JS中 “is not defined” 如何判断defined,defined和undefined 的区别

JS中 “is not defined” 我今天找了一些资料和自己试验了各种方法,都不能得到正解,故写了这个问题的解决方案。

首先什么是is not defined?

从字面意思上来讲就是未定义,也就是未申明。就是这个变量(对象)压根就没有。如下:

 
  1. console.log(sojson);//sojson is not defined

可能还一知半解,我们继续往下看。

is not defined 和 undefined 区别。

我们大多数人都知道 undefined  ,却不知道 defined   undefined  是未定义,如下:

 
  1. var so;
  2. console.log(so);//undefined
  3. console.log(so.a);//so.a is undefined

这个时候输出的是 undefined  。访问变量的属性就会提示is undefined 就是这个变量so 未定义值(类型);

defined 呢,如下:

 
  1. 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 。

我们自己定义对象的时候,对外要提供方法,如下:

 
  1. //申明局部变量 so。
  2. var so = {
  3. a : function(){};
  4. }
  5. //对外提供访问。
  6. window.so = so;

如何判断 undefined。

undefined 很好判断,如下:

 
  1. var sojson;
  2. console.log(sojson == undefined);//true
  3. console.log(sojson === undefined);//true;
  4. console.log(typeof sojson == 'undefined');//true
  5. console.log(typeof sojson === 'undefined');//true
  6. console.log(!sojson);//true
  7. //... ...

如何判断is not defined

我在网上没找到合适的资料来判断“is not defined”,我项目中因为是公共js需要解决,对象是否定义。都不好判断。所以我用比较low的方式来判断的,如果你有好的点子,请留言或者告知我,我加上。

 
  1. try{
  2. var x = sojson.demo;
  3. }catch(e){
  4. console.log(e.message);//sojson is undefined
  5. }

因为抛出了Exception ,所以能catch ,进入了catch 模块。如果有多个,请分开cache ,如下:

 
  1. try{
  2. var x = sojson.demo;
  3. }catch(e){
  4. console.log(e.message);//sojson is undefined
  5. }
  6. try{
  7. var y = sojson.y;
  8. }catch(e){
  9. console.log(e.message);//sojson is undefined
  10. }

因为出现一个 Exception  ,就不会往下执行了,所以要分开去处理。

原文地址:https://www.cnblogs.com/Alex80/p/12509391.html