我正在尝试将对 jQuery
对象的引用传递给模块,但收到一个错误消息:Uncaught TypeError: undefined is not a function
我正在研究 fiddle
以尝试理解我看到的这种模式,以及理解原型(prototype)和 new 关键字。
我不确定是什么导致了这个错误。这是我的 HTML
和 JavaScript
以及一个 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
编写更多模块。因此,如果我还有其他不正确的地方,请告诉我。谢谢!
最佳答案
您在运行使用 MyClass 的代码后定义 MyClass。此外,将您的类塞入变量而不是将其声明为“传统”方式会导致一些问题。试试这个:
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。把它们放在后面。
关于javascript - 未捕获的类型错误 : Undefined is not a function JavaScript Module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21297908/