I have this (very simple) code:
Array.prototype.test = function(x) { alert(x) }
[0].test('Hello, World!')
However, when I execute it, I get this:
TypeError: Cannot call method 'test' of undefined
What is wrong?
I have this (very simple) code:
Array.prototype.test = function(x) { alert(x) }
[0].test('Hello, World!')
However, when I execute it, I get this:
TypeError: Cannot call method 'test' of undefined
What is wrong?
I ran into this this odd error, and I finally figured out that the solution is to add semicolons:
Array.prototype.test = function(x) { alert(x) };
[0].test('Hello, World!');
Otherwise, it would be parsed like this:
Array.prototype.test = function(x) { alert(x) }[0].test('Hello, World!')
function(x) { alert(x) }[0]
is undefined because function objects don't have a property called 0
, so it becomes
Array.prototype.test = undefined.test('Hello, World!')
Then, it tries to call test
on undefined
, which it of course can't do, so it gives an error.