Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the behaviour of the typeof operator in Javascript

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 operator is called both on foo = "hi" and bar = new String("hi").

typeof bar returns "object" but I want it to return "string".

I know this can be done by declaring my own function or accessing the constructor name but I want to modify the behaviour of typeof operator.

EDIT - I am looking for some code that I can add say at the beginning of the program which modifies the behaviour of all the typeof operators in the rest of the program.

like image 805
everconfusedGuy Avatar asked Jun 27 '13 02:06

everconfusedGuy


2 Answers

That is impossible. The behaviour of native operators cannot be changed.

Related links:

  • Why hasn't operator overloading been added to ECMAScript? at quora.com
  • The ES value proxy proposal. It doesn't let you change the existing functionality of typeof, but would enable you to define your own additional types.
like image 188
Bergi Avatar answered Sep 30 '22 07:09

Bergi


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');.

like image 35
Karl-André Gagnon Avatar answered Sep 30 '22 05:09

Karl-André Gagnon