Search code examples
javascriptnode.jsbrowserifyrequire

Browserify context when setting a prototype self executing function with require


I have a "class" like so:

function Person(params) {
   this.params = params;
}

and I would like to define prototypes like this:

Person.prototype.talk = require("./talk.js")(options);

and inside talk.js:

module.exports = exports = function(options) {

     console.log(this); // window here not person

     return {};
};

but inside talk.js this is not referring to the new Person object created... the context is window

This has to do because the require is being passed some settings... Is there any way to pass / preserve the context inside talk.js ?


Solution

  • The problem is not related to the require(...) call, it's related to when and how the exported function is called.

    When you do

    Person.prototype.talk = require("./talk.js")(options);
    

    you're "requiring" (importing...) the code from "talk.js", which is a function, which you the immediately invoke with a parameter (options), but without any context object so the default (window) is used.

    What you apparently want is to have an instance available as the this inside the function, but at the time you call it, there is no instance of the Person class available.

    When you'll later call talk() on an instance, an instance will exist as the this value.

    If you want talk to be the logging function, simply set it in the prototype without invoking it:

    Person.prototype.talk = require("./talk.js");
    
    // later...
    var p = new Person("some parameter");
    p.talk("some option"); // <- this will log the instance.