everconfusedGuy
everconfusedGuy

Reputation: 2797

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.

Upvotes: 5

Views: 4423

Answers (4)

Bergi
Bergi

Reputation: 665574

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

Related links:

Upvotes: 5

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33880

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

Upvotes: 2

Aadit M Shah
Aadit M Shah

Reputation: 74244

No, you can't modify the behavior of typeof or any other operator for that matter. However the next best solution is to use Object.prototype.toString as follows:

function typeOf(value) {
    return Object.prototype.toString.call(value).slice(8, -1);
}

Now you can use it as follows (see the demo - http://jsfiddle.net/CMwdL/):

var foo = "hi";
var bar = new String("hi");

alert(typeOf(foo)); // String
alert(typeOf(bar)); // String

The reason this works is given in the following link: http://bonsaiden.github.io/JavaScript-Garden/#types.typeof

Upvotes: 0

HMR
HMR

Reputation: 39360

typeof is an operator in JavaScript so I'm quite sure you can't. To detect if something is a string you could use something like this:

var s = "hello";
console.log(s.substr&&s.charAt&&s.toUpperCase==="".toUpperCase)//true
s = new String("hello");
console.log(s.substr&&s.charAt&&s.toUpperCase==="".toUpperCase)//true

Upvotes: 1

Related Questions