0

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?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
user1083320
  • 1,836
  • 8
  • 22
  • 29
  • all that means is it's calling a function from an object – aaronman Aug 06 '13 at 16:36
  • `$` is not a custom "syntax". `$` is a valid character for an entity name in Javascript. – Nadh Aug 06 '13 at 16:36
  • possible duplicate of [Why is "$" a valid function identifier?](http://stackoverflow.com/questions/4795551/why-is-a-valid-function-identifier) – Bergi Aug 06 '13 at 16:39

5 Answers5

2

That syntax is just a method call on an object:

var $$ = {
    myFunction: function () {
        return "hello";
    }
};

$$.myFunction(); // hello
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
1

$ 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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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");
    }
};
Dancrumb
  • 26,597
  • 10
  • 74
  • 130
0
$$ = function() {

};

$$.myFunction = function() {

};
Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
0

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/

talemyn
  • 7,822
  • 4
  • 31
  • 52