未捕获类型错误:未定义不是函数JavaScript模块 [英] Uncaught Type Error: Undefined is not a function JavaScript Module

查看:114
本文介绍了未捕获类型错误:未定义不是函数JavaScript模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将对 jQuery 对象的引用传递给模块,并且收到错误消息:未捕获TypeError:undefined不是函数

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.

我不确定导致此错误的原因。这是我的 HTML JavaScript 以及小提琴

I am not sure what is causing this error. Here's my HTML and JavaScript along with a 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;
    };    
}());

我正在尝试用 JavaScript编写更多模块。所以,如果我有其他不正确之处,请告诉我。谢谢!

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!

推荐答案

在运行使用MyClass的代码后,您正在定义MyClass。此外,将您的类填充到变量而不是将其称为传统方式会导致一些问题。试试这个:

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));
});

此外,移动 MyClass.prototype。实际MyClass中的定义。把它们放在后面。

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

这篇关于未捕获类型错误:未定义不是函数JavaScript模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆