Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept calls to constructor

I am having a bit of trouble intercepting constructor calls to a library (so I can replay them later) while still maintaining the prototype chain. More concretely, I am working with a library (ThreeJS, but could be any library), and some code that uses this library. What I want to do is write a piece of code that modifies the library objects, so I can run a block of code every time a constructor is called.

Example: when a new scene is created, I want to print "new Scene created" to the console.

var scene = new THREE.Scene();

When the constructor takes arguments, I also want to log these arguments.

like image 592
Mathias Bak Avatar asked Oct 30 '25 19:10

Mathias Bak


1 Answers

I'm not sure about this, but... you could try something like...

// Backup the original constructor somewhere
THREE._Scene = THREE.Scene;

// Override with your own, then call the original
THREE.Scene = function() {
  // Do whatever you want to do here..
  THREE._Scene.apply(this, arguments);
}

// Extend the original class
THREE.Scene.prototype = Object.create(THREE._Scene.prototype);
like image 143
bvaughn Avatar answered Nov 02 '25 10:11

bvaughn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!