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!

Answers:

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.

Answer

For what it is worth, a lot of the time when I see this problem I find that I have inadvertently called a function before it was referenced in the html. For example, I just called a jquery method in a js file before I loaded my jquery files. Putting the jquery references further up on the page solved it.

Answer

None of the above answers worked for me. But of course, my problem was special. I was recycling an old project to make a new one and there was a method that made the class that I had forgotten about (and was passing in a string instead of a function), and the fact that it wasn't updated was giving me this error, even though I had the syntax elsewhere all correct.

Moral: if you try the above solutions and it still doesn't work, desk check and make sure everyplace where the surrounding method is called passes in the right parameters.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.