Mdd Mdd - 23 days ago 11
jQuery Question

Uncaught Type Error: Undefined is not a function JavaScript Module

I am trying to pass a reference to a

jQuery
Object to a module and have been getting an error that says: Uncaught TypeError: undefined is not a function

I am working on a
fiddle
to try and understand this pattern that I saw, as well as to understand prototype and the new keyword.

I am not sure what is causing this error. Here's my
HTML
and
JavaScript
along with a
fiddle
.

Fiddle.

HTML:

<div class="js-container" data-options="true"></div>
<div class="js-container" data-options="false"></div>


JavaScript:

$('.js-container').each(function (i, element) {
new MyClass($(element));
console.log($(element));
});
var MyClass = (function ($element) {
this.$element;
console.log(this.$element);
this.init();
MyClass.prototype.init = function () {
this.addText();
return this;
};
MyClass.prototype.addText = function () {
var optText = this.$element.attr('data-options');
this.$element.text(optText);
return this;
};
}());


I am trying to learn to write more module with
JavaScript
. So please let me know if I have anything else that is incorrect. Thanks!

Answer

You are defining MyClass after you run the code that uses MyClass. Also, stuffing your class into a variable rather than declaring it the "traditional" way causes some problems. Try this:

function MyClass ($element) {

  this.$element;
  console.log(this.$element);

  // more code...
}

$('.js-container').each(function (i, element) {
  new MyClass($(element));
  console.log($(element));
});

Also, move your MyClass.prototype. definitions out of the actual MyClass. Put them after.