简体   繁体   中英

Writing a function that checks if the parameter is an object literal OR a function OR a string value

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');
        }
    }

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);
}

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:

  • Callable non-instance of Function: document.createElement('object')
  • Non-callable instance of Function: Object.create(Function.prototype)
  • Callable instance of Function: function(){}

An object

  • Object

     Object(value) === value 
  • Non-callable object

     Object(value) === value && typeof value !== 'function' 
  • Instance of Object

     value instanceof Object 

Examples:

  • Callable instance of Object: function(){}
  • Non-callable instance of Object: []
  • Non-callable non-instance of Object: Object.create(null)

Note that typeof value === 'object' is not a reliable way to detect objects, because

  • It produces false negatives for callable objects
  • It produces false positives for null
  • It may produce false negatives for non-callable host objects

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:

  • Primitive string: "abc"
  • String exotic object instance of String: new String("abc")
  • Non-string exotic object instance of String: Object.create(String.prototype)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM