william007
william007

Reputation: 18545

Calling array prototype function

I tried in chrome, what is the reason of not ok below?

 Array.prototype.ts= function () {
          alert("hallo")
      }

[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].ts(); //not ok - what is the reason?
([1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0]).ts(); //ok

Upvotes: 0

Views: 40

Answers (3)

Touffy
Touffy

Reputation: 6561

Runthis is correct, although I'd like to explain why.

Semicolons are generally not useful in JavaScript, but cases like this illustrate the risk of not using them:

  • A function declaration is a valid expression.

  • An expression followed by something in brackets ([]) is also a valid expression.

So the two lines are interpreted as one single expression, and what looks like an array litteral on the second line is in fact read as an invalid indexing of the function object. I would recommend adding a semicolon at the beginning of any line that starts with [ or ( in your code (unless it's meant to continue the previous line, of course).

In other words, your code is read as:

Array.prototype.ts= function () { /*…*/ }[1, 9 /* etc */].ts();

Upvotes: 1

benadaephondelat
benadaephondelat

Reputation: 23

Both of them are executed when I run it :) As far as I know you should avoid extending the Array prototype, because it can change it's default behaviour. You can write an "ordinary" function which does the exact same thing, just check if the input parameter is an array before start doing anything else(Array.isArray(yourArray)), that way you will not pollute anything with unnecessary functions.

Upvotes: 0

Jesse
Jesse

Reputation: 2830

You are missing the semi-colon after the function declaration. Here is what I am running in my chrome console and I am seeing everything work as it should. See below with fiddle

Array.prototype.ts = function() { alert('test') };
[1,2,3].ts()

Upvotes: 2

Related Questions