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'
ofundefined
Why so? How can I fix this?
You're missing a semicolon:
Array.prototype.method1 = function() {
console.log("method1 called");
}; // <--- Hi there!
[1,2,3,4].method1();
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With