I am bit confused with namespaces of function in javascript. Can I have function with same names?
Thanks
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With