简体   繁体   English

覆盖现有的JavaScript Array.prototype方法会导致无限递归吗?

[英]Overriding existing JavaScript Array.prototype method causes infinite recursion?

I know that pop() is a built in method in JavaScript arrays. 我知道pop()是JavaScript数组中的内置方法。 I was just playing around and for kicks decided to override the built in prototype method and encountered this scenario and have no explanation to what is going under the hood. 我只是在玩耍,踢了脚步就决定要覆盖内置的原型方法,并遇到这种情况,并且无法解释到底发生了什么。

When ran the code below in a Node REPL or from a file, it creates in an infinite recursion in my Windows 10 system. 在节点REPL中或从文件中运行以下代码时,它在Windows 10系统中以无限递归方式创建。 The version of Node I am running is v.8.9.1. 我正在运行的Node的版本是8.9.1。

Array.prototype.pop = function() {
  console.log(this);
}

const a = [1, 2, 3];

a.pop();

If someone can explain this phenomenon it would be amazing! 如果有人可以解释这种现象,那就太神奇了!

I think it is something within node engine. 我认为这是节点引擎中的东西。

If I use V8 engine, it works as predicted. 如果我使用V8引擎,它会按预期工作。
https://tio.run/##y0osSyxOLsosKNEts/j/37GoKLFSr6AovyS/pLIgVa8gv0DBViGtNC@5JDM/T0NToZpLQSE5P684PydVLyc/XaMkI7NY05qrlosLJFqikAhUHm2oo2Cko2Aca82VCDJBQ/P/fwA https://tio.run/##y0osSyxOLsosKNEts/j/37GoKLFSr6AovyS/pLIgVa8gv0DBViGtNC@5JDM/T0NToZpLQSE5P684PydVLyc/XaMkI7NY05qrlosLJFqikAhUHm2oo2Cko2Aca82VCDJBQ/P/fwA

But not with node engine. 但不是使用节点引擎。

Plus: 加:
If you change pop with slice , it works just fine regardless the engine. 如果您使用slice更改pop ,则无论引擎如何,它都可以正常工作。

So we might just deduce that it is a bug within node in Array.prototype.pop 因此,我们可以推断出这是Array.prototype.pop节点内的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM