我的家釀功能,以確定變量「類型」?它也可以決定自定義對象的類型:基於變量,你也可以做的constructor屬性
function whatType(somevar){
return String(somevar.constructor)
.split(/\({1}/)[0]
.replace(/^\n/,'').substr(9);
}
var num = 43
,str = 'some string'
,obj = {}
,bool = false
,customObj = new (function SomeObj(){return true;})();
alert(whatType(num)); //=>Number
alert(whatType(str)); //=>String
alert(whatType(obj)); //=>Object
alert(whatType(bool)); //=>Boolean
alert(whatType(customObj)); //=>SomeObj
:
function isType(variable,type){
if ((typeof variable).match(/undefined|null/i) ||
(type === Number && isNaN(variable))){
return variable
}
return variable.constructor === type;
}
/**
* note: if 'variable' is null, undefined or NaN, isType returns
* the variable (so: null, undefined or NaN)
*/
alert(isType(num,Number); //=>true
現在alert(isType(customObj,SomeObj)
返回false。但是如果SomeObj是一個普通的構造函數,它將返回true。
function SomeObj(){return true};
var customObj = new SomeObj;
alert(isType(customObj,SomeObj); //=>true
http://stackoverflow.com/questions/899574/which-is-best-to-use-typeof-or-instanceof – cletus 2010-05-12 08:06:01
我不是在尋找不同的差不多重複的,我知道他們是如何表現。我想知道這是他們之間最安全的解決方案,爲什麼 – mck89 2010-05-12 08:07:53
安全?你的意思是準確的嗎? – kennytm 2010-05-12 08:08:23