1

Maybe this is a simple question but I could not find anything on google or this site. So if I have

var myNamespace = {

    foo: function() {
    },

    bar: function() {
    }
};

how would i load both foo() and bar() without having to do it one by one, e.g.

<script type="text/javascript">
    $(document).ready(function(){
        myNamespace.foo();
        myNamespace.bar();
        .
        .
        .
    });
</script>

3 Answers 3

2
for (var k in namespace) {
    if (typeof namespace[k] === 'function') {
        namespace[k]();    
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think this will fail if something in the namespace isn't a function.
2
var func;

for (func in namespace) {
   if (namespace.hasOwnProperty(func) {
       if (typeof namespace == 'Function') {
           namespace[func]();
       }
   }
}

1 Comment

I think it's a bad idea to use reserved word function as a variable name.
1

I've not tested this, but something like this should prove useful. Every function in JavaScript has a call() method for invoking it. Then:


$(document).ready(function() {
  $.each(myNamespace, function(index, obj) {
    if (typeof(obj) == 'function')
    {
       obj.call(myNamespace);
    }
  });
});

If you need to replace the this scope reference, you could patch this up with jQuery.proxy.

1 Comment

1. 'Function' should be 'function'. 2. You need to provide the context namespace to the call method.

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.