Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why modifying `Array.prototype` doesn't work?

Tags:

javascript

Please refer - https://jsfiddle.net/53ranmn5/1

Array.prototype.method1 = function() {
console.log("method1 called");
}
[1,2,3,4].method1();

I get the following error,

TypeError: Cannot read property 'method1' of undefined

Why so? How can I fix this?

like image 649
gopal rao Avatar asked Dec 25 '22 20:12

gopal rao


1 Answers

You're missing a semicolon:

Array.prototype.method1 = function() {
    console.log("method1 called");
}; // <--- Hi there!
[1,2,3,4].method1();

What?

Semicolons are optional in javascript, so the code you wrote is equivalent to:

Array.prototype.method1 = function() { ... }[1,2,3,4].method1();
// after evaluating the comma operator:
Array.prototype.method1 = function() { ... }[4].method1();
// naturally, functions don't have a fourth index
undefined.method1();
// Error :(

Be careful with your semicolons!

Some reading material:

  • What does a comma do?
  • What are the rules for Javascript's automatic semicolon insertion (ASI)?
  • http://inimino.org/~inimino/blog/javascript_semicolons
  • Specification: Latest stable (es5), Draft (es2015).
like image 164
Zirak Avatar answered Jan 01 '23 21:01

Zirak