1.2.6.2.「typeof」、「instanceof」與搞清楚這是什麼

  • typeof

    • 告訴你型別是甚麼

      var a = 3;
      //印出Number
      console.log(typeof a);
      
      var d = [];
      //印出Object
      console.log(typeof d);
  • 用陣列在原型鍊上呼叫toString

    • call: 將this重新指向d並傳入其他參數, 並執行函數

    • toString會用this變數輸出他的值

      //印出[object Array]
      console.log(Object.prototype.toString.call(d));
  • instanceof

    • 告訴你型別是甚麼

      var e = new Person('Jane');
      //true
      console.log(a instanceof Person);
  • undefined, null

    • bug: typeof null是object

      //印出undefined
      console.log(typeof undefined);
      //印出object
      console.log(typeof null);
  • empty function

      var z = function(){}
      //印出function
      console.log(typeof z);

Last updated