开发者

whats wrong with this code? I am not able to extend the Number object

开发者 https://www.devze.com 2023-03-22 20:45 出处:网络
Number.prototyp开发者_JAVA百科e.xx = function(){ alert(\"hi\"); } 5.xx(); I am trying to extend Number using prototype.The wrong part:

Number.prototyp开发者_JAVA百科e.xx = function(){
alert("hi");
}

5.xx();

I am trying to extend Number using prototype.


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:

  • What does 1..something mean in JavaScript?


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();


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


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

var num = 5;
num.xx();

(5).xx();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号