How do I create custom syntax/prefix for my functions?
jQuery uses $.function
, is there a way I can do that, so say $$.myFunction()
works?
How do I create custom syntax/prefix for my functions?
jQuery uses $.function
, is there a way I can do that, so say $$.myFunction()
works?
That syntax is just a method call on an object:
var $$ = {
myFunction: function () {
return "hello";
}
};
$$.myFunction(); // hello
$
is just a variable name.
var $$ = {
myFunction: function () { ... }
};
… but don't use $$
. $
is a stupid variable name that tells people reading the code absolutely nothing about what it does. $$
has the same problem.
jQuery is just relying on a global object called $
which contains multiple functions.
It can do this because $
is a valid identifier.
You could quite easily do
var $$ = {
myFunction: function() {
console.log("Foo");
}
};
So all of these answers are correct, but none really explains the "why" . . . the "syntax/prefix" that you are talking about is called a "namespace" and the majority of the time that you see it, it is because there has been a JavaScript object that has been defined with a set of methods defined in it.
Some common examples:
Math.round()
- references the round
function within the JavaScript Math object
$.trim()
- references the trim
function for Jquery (which, by default, uses the $
namespace)
Those are the "object forms" of namespacing, but you also pretty regularly see the "object instance" forms as well. For example:
var myDate = new Date();
myDate.getFullYear();
In that example, myDate
is an instance of the JavaScript Date
object, so, by calling myDate.getFullYear();
, you are really namespacing that function to that specific instance of the Date
object, rather than the object itself.
So, to answer your question, if you would like all of your functions to be namespaced, the easiest way to do that is as others have shown . . . create a JavaScript object and make your functions methods of that object.
More on namespacing here: http://addyosmani.com/blog/essential-js-namespacing/