Spencer Carnage
Spencer Carnage

Reputation: 2066

RequireJS and Prototypal Inheritance

I'm running into an issue with using RequireJS and Prototypal inheritance. Here's my module:

define(function () {
  function Module(data) {
    this.data = data;
  }

  Module.prototype.getData = function () {
    return this.data;
  };

  Module.prototype.doSomething = function () {
    console.log(this.data);
    console.log(this.getData());
  };

  return Module;

  Module.prototype.callFunction = function (fn) {
    if (this[fn]) {
      console.log('call');
      Module.prototype[fn]();
    }
  };
});

Then I instantiate the module, like so:

var module = new Module({ name: 'Marty' });
module.getData(); // returns { name: 'Marty' }
module.data; // returns { name: 'Marty' }
module.callFunction('doSomething') // returns undefined on the first (and second) console log

The console.logs in the module.doSomething() always return undefined. Am I misunderstanding how prototypal inheritance works with RequireJS?

Upvotes: 2

Views: 1835

Answers (1)

Spencer Carnage
Spencer Carnage

Reputation: 2066

As it turns out, I had written the callFunction method incorrectly. The correct way is:

Module.prototype.callFunction = function (fn) {
  if (this[fn] && typeof this[fn] === "function") {
    this[fn]();
  }
};

The problem was using Module.prototype instead of this. Whoops.

Upvotes: 2

Related Questions