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?

3
  • all that means is it's calling a function from an object Commented Aug 6, 2013 at 16:36
  • $ is not a custom "syntax". $ is a valid character for an entity name in Javascript. Commented Aug 6, 2013 at 16:36
  • possible duplicate of Why is "$" a valid function identifier? Commented Aug 6, 2013 at 16:39

5 Answers 5

2

That syntax is just a method call on an object:

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

$$.myFunction(); // hello
Sign up to request clarification or add additional context in comments.

Comments

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");
    }
};

Comments

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.

Comments

0
$$ = function() {

};

$$.myFunction = function() {

};

Comments

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/

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.