拦截对构造函数的调用

Mat*_*Bak 3 javascript prototype prototype-chain

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

示例:创建新场景时,我想将"创建新场景"打印到控制台.

var scene = new THREE.Scene();
Run Code Online (Sandbox Code Playgroud)

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

bva*_*ghn 6

我不确定这个,但是......你可以试试像...

// 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);
Run Code Online (Sandbox Code Playgroud)