我在网页上有一个烦人的bug:
date.GetMonth()不是函数
所以,我想我做错了什么。变量date不是date类型的对象。如何在Javascript中检查数据类型?我试图添加一个if(日期),但不起作用。
function getFormatedDate(date) {
if (date) {
var month = date.GetMonth();
}
}
所以,如果我想编写防御性代码并防止日期(不是一个)被格式化,我该怎么做?
谢谢
UPDATE:我不想检查日期的格式,但我想确保传递给getFormatedDate()方法的参数是date类型。
对于所有类型,我都编写了一个Object原型函数。这可能对你有用
Object.prototype.typof = function(chkType){
var inp = String(this.constructor),
customObj = (inp.split(/\({1}/))[0].replace(/^\n/,'').substr(9),
regularObj = Object.prototype.toString.apply(this),
thisType = regularObj.toLowerCase()
.match(new RegExp(customObj.toLowerCase()))
? regularObj : '[object '+customObj+']';
return chkType
? thisType.toLowerCase().match(chkType.toLowerCase())
? true : false
: thisType;
}
现在,您可以像这样检查任何类型:
var myDate = new Date().toString(),
myRealDate = new Date();
if (myRealDate.typof('Date')) { /* do things */ }
alert( myDate.typof() ); //=> String
[编辑2013年3月]基于不断进步的洞察力,这是一种更好的方法:
Object.prototype.is = function() {
var test = arguments.length ? [].slice.call(arguments) : null
,self = this.constructor;
return test ? !!(test.filter(function(a){return a === self}).length)
: (this.constructor.name ||
(String(self).match ( /^function\s*([^\s(]+)/im)
|| [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
}
// usage
var Some = function(){ /* ... */}
,Other = function(){ /* ... */}
,some = new Some;
2..is(String,Function,RegExp); //=> false
2..is(String,Function,Number,RegExp); //=> true
'hello'.is(String); //=> true
'hello'.is(); //-> String
/[a-z]/i.is(); //-> RegExp
some.is(); //=> 'ANONYMOUS_CONSTRUCTOR'
some.is(Other); //=> false
some.is(Some); //=> true
// note: you can't use this for NaN (NaN === Number)
(+'ab2').is(Number); //=> true