Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain namespace in javascript with an example? [closed]

Tags:

javascript

I am bit confused with namespaces of function in javascript. Can I have function with same names?

Thanks

like image 329
Josh Avatar asked Dec 19 '09 20:12

Josh


People also ask

What is namespace in JavaScript with example?

Namespace refers to the programming paradigm of providing scope to the identifiers (names of types, functions, variables, etc) to prevent collisions between them. For instance, the same variable name might be required in a program in different contexts.

What is JavaScript Namespacing How and where is it used?

JavaScript “namespace” is a programming paradigm that is utilized for assigning scope to the identifiers such as variables and function names. It is used to prevent collisions between the same-named variables and functions.

What is the use of a namespace in web development?

Namespace is a context for identifiers, a logical grouping of names used in a program. Within the same context and same scope, an identifier must uniquely identify an entity. In an operating system a directory is a namespace.


1 Answers

There is no official concept of a namespace in Javascript like there is in C++. However, you can wrap functions in Javascript objects to emulate namespaces. For example, if you wanted to write a function in a "namespace" called MyNamespace, you might do the following:

var MyNamespace = {};

MyNamespace.myFunction = function(arg1, arg2) {
    // do things here
};

MyNamespace.myOtherFunction = function() {
    // do other things here
};

Then, to call those functions, you would write MyNamespace.myFunction(somearg, someotherarg); and MyNamespace.myOtherFunction();.

I should also mention that there are many different ways to do namespacing and class-like things in Javascript. My method is just one of those many.

For more discussion, you might also want to take a look at this question.

like image 184
Marc W Avatar answered Sep 23 '22 13:09

Marc W