0

Title may not be correct but I didn't know how to ask my question!

I'm trying to learn writing Object-Oriented in JavaScript and I'm rewriting one of my projects so instead of lots of anonymous functions and duplicated codes I can use methods of classes. Now I'm facing an error on the following code:

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

But I keep facing this error:

TypeError: this.cartModal is undefined

Should I use anything else to use an property inside an object? Or the problem lies somewhere else?

Farid Rn
  • 3,167
  • 5
  • 39
  • 66
  • The problem is that you cannot reference the object during its definition. – Felix Kling Jul 20 '13 at 18:01
  • 1
    @FelixKling So what's the use of `this` if I cannot use that in object definitation? When can I use that? – Farid Rn Jul 20 '13 at 18:02
  • 2
    @faridv — Primarily, inside a function that is used as a method (i.e. like every other use of `this` in your example code). – Quentin Jul 20 '13 at 18:03
  • You can use it in methods of objects to refer to the object. Or to refer to the target element in an event handler. Or to the new object in a constructor function. And more! – Felix Kling Jul 20 '13 at 18:05

2 Answers2

1

The problem comes here: $checkboxes: this.cartModal.find("input[name=check]"),

this does not refer to cart but to the current scope this, you can not refer to your current object when you declare it like that.

Better do:

var modal = $("#cart-modal"),
    cart = {
        cartModal: modal,
        $checkboxes: modal.find("input[name=check]")
        ...
    }
dievardump
  • 2,484
  • 17
  • 21
0

You can't acces the element while making it. Using a function should work.

$checkboxes: function(){return this.cartModal.find("input[name=check]")},

But what you could also do is use an object constructor . There you can use this. to refer to the object you are creating.

function YourObject() {
    this.$checkboxes = this.cartModal.find("input[name=check]");
    .......
}
zoran404
  • 1,682
  • 2
  • 20
  • 37
  • But the OP didn't say he wants `$checkboxes` to be a method. That's what you are doing here. He will have to `cart.$checkboxes()` to access it. And it will query the DOM (using jQuery, bad scenario) every time. – dievardump Jul 20 '13 at 18:07
  • In that case what about using an object constructor. – zoran404 Jul 20 '13 at 18:27