编辑:七年后,这个答案仍然偶尔得到支持。如果您正在寻找运行时检查,那很好,但是我现在建议使用Typescript或可能的Flow进行编译时类型检查。参见https://stackoverflow.com/a/31420719/610585更多信息,上面的。
原始答案:
它不是语言内置的内容,但是您可以轻松地自己完成。Vibhu的答案是我认为Javascript中类型检查的典型方法。如果您想要更一般化的内容,请尝试如下操作:(仅是示例,可以帮助您入门)
typedFunction = function(paramsList, f){
//optionally, ensure that typedFunction is being called properly -- here's a start:
if (!(paramsList instanceof Array)) throw Error('invalid argument: paramsList must be an array');
//the type-checked function
return function(){
for(var i=0,p,arg;p=paramsList[i],arg=arguments[i],i<paramsList.length; i++){
if (typeof p === 'string'){
if (typeof arg !== p) throw new Error('expected type ' + p + ', got ' + typeof arg);
}
else { //function
if (!(arg instanceof p)) throw new Error('expected type ' + String(p).replace(/\s*\{.*/, '') + ', got ' + typeof arg);
}
}
//type checking passed; call the function itself
return f.apply(this, arguments);
}
}
//usage:
var ds = typedFunction([Date, 'string'], function(d, s){
console.log(d.toDateString(), s.substr(0));
});
ds('notadate', 'test');
//Error: expected type function Date(), got string
ds();
//Error: expected type function Date(), got undefined
ds(new Date(), 42);
//Error: expected type string, got number
ds(new Date(), 'success');
//Fri Jun 14 2013 success