标题可能不正确,但我不知道如何提出我的问题!
我正在尝试学习用JavaScript编写面向对象,我正在重写我的一个项目,所以我可以使用类的方法来代替大量的匿名函数和重复代码。现在我在以下代码上遇到错误:
var cart = {
cartModal: $("#cart-modal"),
$checkboxes: this.cartModal.find("input[name=check]"),
// ^^^^^^^^^^^^^^
toggleModal: function(e) {
this.cartModal.modal('toggle');
this.handleCheckboxes();
e.preventDefault();
},
handleCheckboxes: function() {
this.cartModal.find("input.checkall").click(function() {
$checkboxes.prop("checked", !$checkboxes.prop("checked"));
});
}
};
$("#cart-link").click(function(e) {
cart.toggleModal(e);
});
但我一直面临这个错误:
TypeError: this.cartModal is undefined
我应该使用其他任何东西来使用对象内的属性吗?或问题出在其他地方?
答案 0 :(得分:1)
问题来自:$checkboxes: this.cartModal.find("input[name=check]"),
this
不是指cart
,而是指当前范围this
,当你声明它时,你不能引用你当前的对象。
更好:
var modal = $("#cart-modal"),
cart = {
cartModal: modal,
$checkboxes: modal.find("input[name=check]")
...
}
答案 1 :(得分:0)
制作时无法访问该元素。使用函数应该可以工作。
$checkboxes: function(){return this.cartModal.find("input[name=check]")},
但您还可以使用对象构造函数。在那里,您可以使用this.
来引用您正在创建的对象。
function YourObject() {
this.$checkboxes = this.cartModal.find("input[name=check]");
.......
}