RequireJS and Prototypal Inheritance-Collection of common programming errors

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?

  1. 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.

Originally posted 2013-11-09 22:49:23.