拦截对构造函数的调用

Intercept calls to constructor

我在拦截对库的构造函数调用时遇到了一些麻烦(因此我可以稍后重播它们),同时仍保持原型链。更具体地说,我正在使用一个库(ThreeJS,但可以是任何库)和一些使用该库的代码。我想做的是编写一段修改库对象的代码,这样每次调用构造函数时我都可以 运行 一段代码。

示例:创建新场景时,我想在控制台打印"new Scene created"。

var scene = new THREE.Scene();

当构造函数接受参数时,我也想记录这些参数。

我不确定,但是...您可以尝试类似...

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

从@bvaughn 代码开始,这对我有用:

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:", ....