编写一个函数,检查参数是否为对象文字或函数或字符串值

时间:2016-02-14 02:55:17

标签: javascript

我正在学习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');
        }
    }

2 个答案:

答案 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"
  • String的异域对象实例:new String("abc")
  • String的非字符串异域对象实例:Object.create(String.prototype)