Changing the behaviour of the typeof operator in Javascript

前端 未结 4 610
灰色年华
灰色年华 2020-12-20 22:22

I would like to know if there is any way of overriding the behaviour of the typeof operator. Specifically, I want to return \"string\" when the typeof

4条回答
  •  醉话见心
    2020-12-20 23:00

    You can't change a Javascript operator, however you can check if it's a string OR a string object with instanceof.

    var strObj = new String('im a string')
    var str = 'im a string'
    
    alert(strObj instanceof String); //true
    alert(typeof strObj == 'string'); //false
    alert(str instanceof String); //false
    alert(typeof str == 'string'); //true
    alert(strObj instanceof String || typeof strObj == 'string'); //true
    alert(str instanceof String || typeof str == 'string'); //true
    

    Of course, it is much more simple and shorter to create your own function, but if you want to use native JS, that is the way : alert(str instanceof String || typeof str == 'string');.

提交回复
热议问题