Extending THREE objects in r121 Module version

I consider modifying the prototype more of a feature of Javascript though it can get you in trouble. I agree that derived classes are better practice but there are some cases where it’s not possible or just far too cumbersome to do. Specifically the cases I’ve modified the prototype are to add raycast functionality using BVHs for all Mesh and adding an extra event when adding children to performantly track all the objects in a subhierarchy. I usually try to limit the modification to overriding or extending existing functions, though, and use it sparingly. Completely custom functions are riskier because you may wind up overwriting a new function added to THREE with the same name.

@titansoftime

This is the pattern I’ve always used:

import { Mesh } from 'three';

// extending an existing function
const originalRaycast = Mesh.prototype.raycast;
Mesh.prototype.raycast = function(...args) {

    const result = originalRaycast.apply( this, args );

    // custom logic...

    return result;

};

// Or you can add an entirely new function like this
Mesh.prototype.customFunction = function() {};

Can you make a fiddle showing the change in behavior from before and after r121? This should still work.

1 Like