Reputation: 3384
I was learning ngMock and realized that the module method of ngMock takes an argument that can be either a string, OR a function OR an object literal. I was wondering what is the best way to write a similar function using just plain JavaScript and doing the following:
// 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');
}
}
Upvotes: 2
Views: 93
Reputation: 288280
Use the following to test whether value
is
A function
Callable object
typeof value === 'function'
Instance of Function
value instanceof Function
Callable instance of Function
typeof value === 'function' && value instanceof Function
Examples:
document.createElement('object')
Object.create(Function.prototype)
function(){}
An object
Object
Object(value) === value
Non-callable object
Object(value) === value && typeof value !== 'function'
Instance of Object
value instanceof Object
Examples:
function(){}
[]
Object.create(null)
Note that typeof value === 'object'
is not a reliable way to detect objects, because
null
A string
Primitive string
typeof value === 'string'
Instance of String
value instanceof String
String exotic object (may produce false positives)
({}).toString.call(value) === "[object String]" && typeof value !== 'string'
Examples:
"abc"
new String("abc")
Object.create(String.prototype)
Upvotes: 1
Reputation: 46910
Use 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');
}
}
Or better yet
function(argument){
console.log(typeof argument);
}
Upvotes: 3