javascriptprototypeprototype-chain

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.


Solution

  • 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);