Extending Array.prototype in Node.js, from a require'd file

后端 未结 2 430
梦谈多话
梦谈多话 2021-01-06 03:07

I have the following saved in test.js. It successfully extends Array in the browser, but it doesn\'t seem to work with node and require. Can someone explain what\'s wrong

2条回答
  •  没有蜡笔的小新
    2021-01-06 03:28

    Every command in the REPL is executed via vm.runInContext with a shared context object. This object is created at REPL initialization by copying everything from the global object. Since the require'd module will only extend Array.prototype after it has been copied to the context object, the modified version is never exposed.

    Or at least that's what I could deduce from the source code. I know nothing about the inner workings of V8 :) And as you probably have found out by now, your example works fine outside the REPL.

提交回复
热议问题