'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 1:[1]
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);
Solution 2:[2]
Starting from @bvaughn code, this worked for me:
THREE._Scene = THREE.Scene;
THREE.Scene = function() {
const Scene = Function.prototype.bind.apply(THREE._Scene, arguments);
const scene = new Scene()
console.log("Intercepted scene:", scene)
return scene;
}
THREE.Scene.prototype = Object.create(THREE._Scene.prototype);
// Test
const scene = new THREE.Scene()
// Prints "Intercepted scene:", ....
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | tokland |
