Moshe Simantov
Moshe Simantov

Reputation: 4503

Is it possible to read function closure via V8 addon?

I want to write a Node.js V8 addon in C++ that will give me access to functions closures.

Something like this:

const myAddon = require('./build/Release/addon');

const counter = (() => {
  let i = 0;
  return () => ++i;
})();

counter(); // 1
counter(); // 2

const closure = myAddon(counter);
console.log(closure.i); // prints "3"

Is it possible? Where this information stored on the V8 engine?

Upvotes: 2

Views: 213

Answers (1)

Andreas Rossberg
Andreas Rossberg

Reputation: 36118

No, that is not possible. And that's a feature. It allows the engine to optimise local variables in various ways, including eliminating them entirely. Without that ability, JavaScript programs would run substantially slower than they already do. The best you can get is what the debugger interface provides, and that's only a best effort attempt to reconstruct as much information as is still possible. Depending on how a function got optimised it may be incomplete or even wrong.

Also, closures are the only way in JavaScript to express proper encapsulation. Such a library would break that property.

Upvotes: 3

Related Questions