简体   繁体   中英

Overriding existing JavaScript Array.prototype method causes infinite recursion?

I know that pop() is a built in method in JavaScript arrays. 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. The version of Node I am running is v.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.
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.

So we might just deduce that it is a bug within node in Array.prototype.pop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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