Search code examples
javascriptwebpackprototypees6-modules

webpack doesnt add prototype function to Object from other file


I have a file containing the definition of a Object and in that same file I have a function that is part of this object like so:

export function ARScene(_callbacks) {

   this.callbacksObject = _callbacks;
   // more fancy code.. 
}

ARScene.prototype.changeCar = function() {
    //some fancy code here 
    this.loadHDCar(); // THIS LIKE GENERATES A ERROR. 
}

now I have a different file containing an other method that is part of the Object called ARScene like so:

import { ARScene } from './arScene';

ARScene.prototype.loadHDCar = function() {
     //some more fancy code..
}

What is happening when I build this with webpack and run it in the browser I get the error that this.loadHDCar(); is undefined I guess this happens because webpack doesnt add a file if it is not imported. But how do I make sure that ARScene.prototype.loadHDCar is added to the object in the final output?

I am a complete newbie to webpack and modules. I have found answers on stackoverflow about this but they had slightly different scenarios then me. So their solutions didnt work (or maybe I didnt understand it).

If more context or information is needed please let me know.


Solution

  • How do I make sure that ARScene.prototype.loadHDCar is added to the object in the final output?

    You should import it in the arScene module, and you should even create the prototype method in there (where you are defining the class) for visibility.

    export function loadHDCar() {
        … //some more fancy code
    }
    
    import { loadHDCar } from './loadHDCar';
    
    export function ARScene(_callbacks) {
        …
    }
    ARScene.prototype.loadHDCar = loadHDCar;
    ARScene.prototype.changeCar = function() {
        … // some fancy code here 
        this.loadHDCar();
    };