我正在学习ngMock,并意识到ngMock的模块方法接受的参数可以是字符串,也可以是函数或对象文字。我想知道使用纯JavaScript编写类似函数的最佳方法是什么,并执行以下操作:
// PSEUDO CODE
function(argument){
if(argument is function){
console.writeline('Function');
}
else if(argument is object){
console.writeLine('Object');
}
else if(argument is string){
console.writeLine('String literal');
}
}
答案 0 :(得分:3)
使用 typeof
function(argument){
if(typeof argument == 'function'){
console.log('Function');
}
else if(typeof argument == 'object'){
console.log('Object');
}
else if(typeof argument == 'string'){
console.log('String literal');
}
}
或者更好
function(argument){
console.log(typeof argument);
}
答案 1 :(得分:1)
使用以下内容测试value
是否
功能
可调用对象
typeof value === 'function'
功能实例
value instanceof Function
可调用的函数实例
typeof value === 'function' && value instanceof Function
示例:
document.createElement('object')
Object.create(Function.prototype)
function(){}
对象
对象
Object(value) === value
不可调用对象
Object(value) === value && typeof value !== 'function'
对象实例
value instanceof Object
示例:
function(){}
[]
Object.create(null)
请注意,typeof value === 'object'
不是检测对象的可靠方法,因为
null
字符串
原始字符串
typeof value === 'string'
字符串实例
value instanceof String
字符串异域对象(可能产生误报)
({}).toString.call(value) === "[object String]" && typeof value !== 'string'
示例:
"abc"
new String("abc")
Object.create(String.prototype)