JS中 “is not defined” 我今天找了一些資料和自己試驗了各種方法,都不能得到正解,故寫了這個問題的解決方案。
首先什么是is not defined?
從字面意思上來講就是未定義,也就是未申明。就是這個變量(對象)壓根就沒有。如下:
console.log(sojson);//sojson is not defined
可能還一知半解,我們繼續往下看。
is not defined 和 undefined 區別。
我們大多數人都知道 undefined ,卻不知道 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 ,就不會往下執行了,所以要分開去處理。