Doo*_*nob 1 javascript arrays prototype typeerror
我有这个(非常简单的)代码:
Array.prototype.test = function(x) { alert(x) }
[0].test('Hello, World!')
Run Code Online (Sandbox Code Playgroud)
但是,当我执行它时,我得到了这个:
TypeError: Cannot call method 'test' of undefined
Run Code Online (Sandbox Code Playgroud)
怎么了?
我遇到了这个奇怪的错误,我终于弄清楚解决方案是添加分号:
Array.prototype.test = function(x) { alert(x) };
[0].test('Hello, World!');
Run Code Online (Sandbox Code Playgroud)
否则,它将被解析为这样:
Array.prototype.test = function(x) { alert(x) }[0].test('Hello, World!')
Run Code Online (Sandbox Code Playgroud)
function(x) { alert(x) }[0]未定义,因为函数对象没有被调用的属性0,因此它变为
Array.prototype.test = undefined.test('Hello, World!')
Run Code Online (Sandbox Code Playgroud)
然后,它试图调用test上undefined,这当然是不能做的,所以它提供了一个错误.
| 归档时间: |
|
| 查看次数: |
594 次 |
| 最近记录: |