2

(function($){

    $.a.b  = {

        title: "ABC",

        init: function (id) {
                 /* do something here */
                  return id+'a';

              }




    };

})(jQuery);

When I try to call $.a.b.init('t'); it does not work, I mean it does not return as expected. Any suggestions?

The problem is not that $.a.b.init('t') is not working. Problem is that it returns the code of the whole function instead of returning say a string.

Thank you for your time.

1
  • The code as posted works well, besides the $.a.b thing: jsbin.com/eqaji . Typically, you'll get the source of the function if you don't start it, e.g. alert($.a.b.init); and not alert($.a.b.init('parameter'));, so there isn't much more I can think of without more code. Commented Sep 21, 2009 at 16:34

2 Answers 2

7

try

$.a = [];
$.a.b  = { ... }

or even better:

$.a = {b: {
     title: "",
     init: ...
}};

When using $.a.b a is undefined, so you cannot add to it.

Sign up to request clarification or add additional context in comments.

1 Comment

@Ramblingwood - invaluable tool. But even the error console can help here: Ctrl+Shift+J on Firefox.
4

Since $.a is not yet defined you cannot set the b property. First you'll need to create $.a. Alternatively, use a namespacing helper:

$.namespace = function(ns) {
    var cur = $, split = ns.split('.');
    while (split[0]) {
        cur = cur[split.shift()] = {};
    }
    return cur;
};

$.namespace('a').b = { ... };

It can also be used with deeper namespaces:

$.namespace('a.b.c.d.e.f').g = 123;
$.a.b.c.d.e.f.g; // => 123

1 Comment

Interesting and weird. I guess if you use that a lot you can add it for all objects, not just jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.