Pete_ch
Pete_ch

Reputation: 1321

jquery object literal function / closure - missing something obvious?

How can I get this to work? seems to be a trivial mistake Im not seeing

   (function($){
      $.myNamespace = {
        num:0,
        incNum: function(){
                  return num++;},
        decNum: function(){
                  return num--;},
        getNum: function(){
                return num;
                }
      };
    })(jQuery);

calling $.myNamespace.incNum gives a 'ReferenceError: num is not defined'

Upvotes: 0

Views: 280

Answers (4)

Abhidev
Abhidev

Reputation: 7253

'num' is inside your parent class 'myNamespace'...and if you want to access it form the children methods of this class then as @Kieran said you need to use the this keyword, i.e this.num++

Upvotes: 0

Ry-
Ry-

Reputation: 224932

num isn't part of the function's scope; JavaScript has no concept of namespaces. Instead, you should access num as $.myNamespace.num or this.num (though I don't recommend that - this can be bound to arbitrary objects.)

Upvotes: 0

xdazz
xdazz

Reputation: 160853

(function ($) {
    $.myNamespace = {
        num: 0,
        incNum: function () {
            return this.num++;
        },
        decNum: function () {
            return this.num--;
        },
        getNum: function () {
            return this.num;
        }
    };
})(jQuery);

Upvotes: 1

Kieran Andrews
Kieran Andrews

Reputation: 5885

You have to edit all of the return statements to reference the object.

 return this.num++;

So your code will look like this:

(function ($) {
    $.myNamespace = {
        num: 0,
        incNum: function () {
            return this.num++;
        },
        decNum: function () {
            return this.num--;
        },
        getNum: function () {
            return this.num;
        }
    };
})(jQuery);

Upvotes: 0

Related Questions