Konrad Viltersten
Konrad Viltersten

Reputation: 39190

Unable to call the declared prototype on Number while String works in JavaScript

I've declared two methods.

String.prototype.hazaa = function (shazoo) {
  return this + shazoo;
}

Number.prototype.hazaa = function (shazoo) {
  return this + shazoo;
}

When I call the former, I get the expected behavior. However, invoking the second one, produces the error below.

Syntax error: Unexpected token ILLEGAL(...)

I have the feeling that it's my C#-ishness that is spooking (I'm thinking extension methods and object oriented calls). The invocation's performed as follows.

"abc".hazaa("shazoo");
12345.hazaa(00000000);

Is there another syntax to invoke the function I've added? Have I not declared the prototype addition the right way?

Yes, I have made the research but I might be missing a relevant point.

Upvotes: 1

Views: 38

Answers (1)

James Thorpe
James Thorpe

Reputation: 32212

The issue is while it is parsing 12345.hazaa(00000000);, it sees hazaa as coming after the decimal point in the number, hence the unexpected token. If you wrap the number in parentheses it is parsed and executed correctly:

(12345).hazaa(00000000);

It will continue to work normally on variables, as the parsing has already happened:

var a = 123;
a.hazaa(0000);

As mentioned by Jaromanda X in the comments, another alternative to allow correct parsing is to use a double-dot syntax:

12345..hazaa(00000000);

Upvotes: 3

Related Questions