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  ,就不會往下執行了,所以要分開去處理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM