What's the difference between using instanceof and checking the constructor?

后端 未结 2 954
傲寒
傲寒 2020-12-03 22:48

Why do the following two lines return different results?

(\"test\" instanceof String) // returns false
(\"test\".constructor == String) // returns true
         


        
2条回答
  •  旧时难觅i
    2020-12-03 23:28

    The main difference is that instanceof inspects the object's prototype chain whereas checking the constructor only checks to see if it was created from the same constructor.

    Example:

    function MyObject() {
        this.sayHi = function() { alert('Hi!'); }   
    }
    
    var x = new MyObject();
    alert(x.constructor === Object);
    alert(x instanceof Object);
    

提交回复
热议问题