Why are some JavaScript constructors not functions?

前端 未结 3 1205
闹比i
闹比i 2021-02-14 19:43

Clarification:
\"JavaScript constructor\" should be more properly be written as \"javascript constructor\" to emphasize that the constructors considered are not just the nat

3条回答
  •  离开以前
    2021-02-14 20:42

    First:

    Objects ARE functions

    No, the are not:

    > a = function() {}
      function () {}
    > a instanceof Object
      true
    > b = {}
      Object
    > b instanceof Function
      false
    

    The toString method (which is what gets called when you do string concatenation) is not a reliable way to get information about an object. If I use typeof, I get the following:

    using browser environment:  
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:5.0.1) Gecko/20100101 Firefox/5.0.1
    
    function
    
    function
    
    function
    
    object
    
    function
    
    function
    
    function
    

    So you see, most of them, apart form Storage, are actually functions (why it does not work for Storage, I don't know).

    Also keep in mind that the DOM interface can behave differently than native JavaScript objects.

    On the other hand, in Chrome the toString method gives this:

    [object Function] 
    
    [object Function] 
    
    [object Function] 
    
    function Storage() { [native code] } 
    
    function XMLHttpRequest() { [native code] } 
    
    function Worker() { [native code] } 
    
    function FileReader() { [native code] }
    

提交回复
热议问题