Skip to content Skip to sidebar Skip to footer

Whats Wrong With This Code? I Am Not Able To Extend The Number Object

Number.prototype.xx = function(){ alert('hi'); } 5.xx(); I am trying to extend Number using prototype.

Solution 1:

The wrong part:

5.xx();

This causes a syntax error, because the dot is taken as part of the number literal notation, in fact, the decimal part is not required, and for example, var a = 5.; is a valid numeric literal.

Try:

(5).x(); // or
5..xx();

Related:


Solution 2:

The problem is a rather quirky bit of Javascript syntax. There's nothing wrong with extending the Number prototype in the way that you do if the browser supports it (other than the inherent problems of extending native types).

The problem is that any . immediately after a number literal is treated as being a decimal point. So it sees 5. and expects a decimal number, then throws up when it sees xx. You need to use one of the alternative syntaxes for this.

(5).xx();
5..xx();
5 .xx();

Solution 3:

This will work. It is a flaw in the JS parser

5..xx()
(5).xx()

You can read about this and other quirky parts of the JavaScript programming language in JS Garden


Solution 4:

Both of these approaches will work (given your xx function above):

var num = 5;
num.xx();

(5).xx();

Post a Comment for "Whats Wrong With This Code? I Am Not Able To Extend The Number Object"