0

what purpose of such pattern?

var ns=function(){
  //do some stuff
}

ns.test=function(){
  //do another stuff
}

I saw code that is similar to that, but I don't understand advantages of such pattern.

Also seems like this is similiar to properties of objects.

also this pattern some times used with closures, and it seems that jquery uses it, but not sure about that.

Thanks!

2 Answers 2

1

For one thing, it ensures that your variable and function names do not clash with names from other scripts that may be included (like advertising, analytics, libraries that don't namespace etc).

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

2 Comments

so these two functions technically not relative each other?
Well, the way that it works is ns is a function (and an object, since functions are first-class in Javascript), and it closes over the other properties such as ns.test, which also happens to be a function. So the function test belongs to the object ns.
0

This pattern arises because in JavaScript, functions are first-class objects with their own properties and methods. This allows functions to be executed by themselves, but also mimic things in other languages. This allows you to do some pretty powerful things like mimicing static classes, memoization, namespacing, etc.

Comments

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.