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
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");
}
};
$ 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.
$$ = function() {
};
$$.myFunction = function() {
};
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/
Related
This question already has answers here:
How does jQuery makes the jQuery object both a function and an object property?
(3 answers)
Closed 7 years ago.
If $ is an object then how is jQuery able to call it with parenthesis (), like $('#MYdIV'). That is my first and most important question.
I am trying to learn design patterns, and underlaying mechanisms of creating an object. So I want to make library that when user type myLibrary({option1:true}); he would be able to instantiate an object without using keyword new.Just like jquery and this: https://github.com/bendc/animateplus/blob/master/animate.js
In this example he is not using keyword new nor this. He is just creating IIFE animate which returns another function with the same name. I don't know how is he able to do that. Is animate bound to global object?
jQuery or $ is just a function. Consider the following example which produces an object with the similar behavior.
Of course, jQuery has the much more complex and smart structure, this is just an example:
var not$ = function(o) {
var result = document.querySelectorAll(o);
result.customInnerText = function(text) {
if (text === undefined) {
return document.querySelector(o).innerText;
} else {
document.querySelector(o).innerText = text;
}
};
result.customClickHandler = function(callback) {
document.querySelector(o).addEventListener('click', callback);
};
return result;
};
not$.customConsoleLog = function(text) {
console.log(text);
};
not$("a").customClickHandler(function() {
var exampleText = not$("#title").customInnerText();
not$("#text").customInnerText(exampleText + "It works!");
not$.customConsoleLog(not$("p").length);
not$.customConsoleLog(not$("p")[0]);
});
Click me!
<p id="title">Example:</p>
<p id="text">Check!</p>
First a few terms:
a primitive is one of the following: string, number, boolean, null, undefined, symbol
An object is essentially any kind of thing that's not a primitve in Javascript. If it's a thing you want to use or manipulate, it's an object.
A function is a particular type of object that can be used to run javascript. This can be called by using the syntax function()
A constructor is just a function. It's a function which is intended to be called with the new keyword, as in new Thing(). Note the capital letter - that's convention.
So we can see that JQuery uses a function, not a constructor function. Specifically, if you look into the source code we'll find something like $ = function() {...}
And that's basically it - they define a global variable called $ and define it to be a function that can be used. Of course, since functions are objects, you can also do things like $.randomNumber = 4 without problems, and it won't affect JQuery in the slightest.
So if you're wanting to do something similar, you'll want to define your own global variable and set it as a function - just be aware of what's already taken - i.e. don't use $ or _ or whatever.
(1) $ is not an object, but a function.
console.log(typeof $);
// function
What might be confusing here - and this is just a guess - is that you can access properties on the $ variable, e.g. $.extend or $.fn (used when writing your own jQuery plugins). This is normal, as functions can have properties themselves. The ECMAScript specifications allow that.
(2) Constructor functions can be used to create new objects, but are not required. You can just used object literals, and that works just as well. As pointed out by #Jeff in the other answer, a function invoked with new makes it a constructor function. Otherwise, there is no difference in the syntax. It is up to you to pick whether you wish to use.
Today while working my mind was stack at some point in javascript.
I want to know that what is basic difference between
function FunctionName(){
//Code goes here;
}
And
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
//Code goes here;
}
Both are working same. Then what is difference between then. Is there any advantage to use function with object name?
I have read Question. But it uses variable and assign function specific variable. I want to create object and assign multiple function in single object.
The first one defines a global function name. If you load two libraries, and they both try to define FunctionName, they'll conflict with each other. You'll only get the one that was defined last.
The second one just has a single global variable, MyFuncCollection. All the functions are defined as properties within that variable. So if you have two collections that try to define the same function name, one will be FuncCollection1.FunctionName, the other will be FuncCollection2.FunctionName, and there won't be any conflict.
The only conflict would be if two collections both tried to use the same name for the collection itself, which is less likely. But this isn't totally unheard of: there are a few libraries that try to use $ as their main identifier. jQuery is the most prominent, and it provides jQuery.noConflict() to remove its $ binding and revert to the previous binding.
The short answer is, the method in object context uses the Parent Objects Context, while the "global" function has its own object context.
The long answer involves the general object-oriented approach of JavaScript, though everything in JavaScript is an object you may also create arrays with this Method.
I can't really tell you why, but in my experience the best function definition is neither of the top mentioned, but:
var myFunction = function(){};
It is possible to assign function to variables, and you may even write a definition like this:
MyObject.myMethod = function(){};
For further reading there are various online Textbooks which can give you more and deeper Information about this topic.
One main advantage I always find is cleaner code with less chance of overwriting functions. However it is much more than that.
Your scope changes completely inside the object. Consider the following code ::
Function:
function FunctionName(){
return this;
}
FunctionName()
Returns:
Window {top: Window, location: Location, document: document, window: Window, external: Object…}
Object:
var MyFuncCollection = new Object();
MyFuncCollection.FunctionName = function(){
return this;
}
MyFuncCollection.FunctionName()
Returns:
Object {}
This leads to some nice ability to daisy chain functions, amongst other things.
The first:
function functionName (){
//Code goes here;
}
Is a function declaration. It defines a function object in the context it's written in.
Notice: this doesn't have to be the global context and it doesn't say anything about the value of this inside it when it's invoked. More about scopes in JavaScript.
Second note: in most style guides functions are declared with a capitalized name only if it's a constructor.
The second:
var myFuncCollection = {};
myFuncCollection.functionName = function () {
//Code goes here;
};
notice: don't use the new Object() syntax, it's considered bad practice to use new with anything other then function constructors. Use the literal form instead (as above).
Is a simple assignment of a function expression to a property of an Object.
Again the same notice should be stated: this says nothing about the value of this when it's invoked.
this in JavaScript is given a value when the function object is invoked, see here for details.
Of course, placing a function on an Object help avoiding naming collisions with other variables/function declarations in the same context, but this could be a local context of a function, and not necessarily the global context.
Other then these differences, from the language point of view, there's no difference whatsoever about using a bunch of function declarations or an Object with bunch of methods on it.
From a design point of view, putting methods on an Object allows you to group and/or encapsulate logic to a specific object that should contain it. This is the part of the meaning of the Object Oriented Programming paradigm.
It's also good to do that when you wish to export or simply pass all these functions to another separate module.
And that's about it (:
I've been wondering for a long time how jQuery can be both a function and an object property.
You can use it like a function, jQuery(...) and you can use it like a property jQuery.ajax(...)
How can you achieve a such thing in Javascript?
functions are objects in javascript. So you can have your main function
var $ = function() { alert('wat'); }
and then extend it
$.fadeTo = function() { alert('fadeto'); }
Because in JavaScript, functions are objects that can have properties:
function test() { ... }
test.a = function () { ... };
test.a(); // totally valid
I think the concept of what exactly is jQuery in terms of code concepts is quite confusing. I ran across this link, which explains the jQuery Architecture in a very simple and easy manner : http://blog.mikecouturier.com/2010/02/beginning-with-jquery-solid-foundation_22.html
So, in short, $ is an alias for a JavaScript function called 'jQuery', and methods invoked by using a dot notation like $.trim ( ) are static methods on the 'JavaScript 'jQuery' function. Note that a function inherits from object in JavaScript, and so a function is an object in JavaScript.
I've looked at various answers on SO that answer similar questions, but none have really answered what I'm looking for. Examples here:
jQuery prototype and constructor function chaining
How does basic object/function chaining work in javascript?
I'd like to be able to chain methods from a function, but also use that function as a namespace. You can use the jquery object as a function like so:
$('selector');
but you can also reach methods straight from the $ variable, like so:
$.ajax(
How is this achieved? I've tried looking into the jquery source but it's near impossible to follow.
In Javascript functions are first-class objects. In particular, they are objects.
var greet = function(name) {console.log("Hello, " + name + "!"); };
greet.lang = "English";
Is legal. Then the following are both valid:
greet("Alice"); // prints Hello, Alice!
console.log(greet.lang); // prints English
I don't think it's accurate to call $(...) a constructor. In Javascript the line between constructor and function is blurred, but usually I would say a constructor is used with new, and, by convention, starts with a Capital letter. $ is simply an object, and in particular one that is a function, so may be called, and has other properties that may be accessed.
I also wouldn't call $, or in my example greet, a namespace. You may be thinking of the package syntax in Java where com.mycompany.util.StringFunctions would have the package/namespace com.mycompany.util, or in C++ where this might be written as MyCompany::Util::StringFunctions. Javascript doesn't quite have this concept, but in more or less any OO language it can be simulated with objects, as above. I would say $ just feels like it's a namespace because it's a rather huge library, but it's a huge library that is implemented as one object that is also a function, with many properties.
Just try this:
var foo = function (){
alert ("I'm a function beep beep");
};
foo.bar = "This is a string";
foo.otherFoo = function (param) {
alert ("I'm also a function blup blup"+param);
};
Then you can call the first function foo(), the variable foo.baror the second function with a value foo.otherFoo(" and more blup.")
I am just starting out with writing jQuery plugins. I wrote three small plugins but I have been simply copying the line into all my plugins without actually knowing what it means. Can someone tell me a little more about these? Perhaps an explanation will come in handy someday when writing a framework :)
What does this do? (I know it extends jQuery somehow but is there anything else interesting to know about this)
(function($) {
})(jQuery);
What is the difference between the following two ways of writing a plugin:
Type 1:
(function($) {
$.fn.jPluginName = {
},
$.fn.jPluginName.defaults = {
}
})(jQuery);
Type 2:
(function($) {
$.jPluginName = {
}
})(jQuery);
Type 3:
(function($){
//Attach this new method to jQuery
$.fn.extend({
var defaults = {
}
var options = $.extend(defaults, options);
//This is where you write your plugin's name
pluginname: function() {
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
I could be way off here and maybe all mean the same thing. I am confused. In some cases, this doesn't seem to be working in a plugin that I was writing using Type 1. So far, Type 3 seems the most elegant to me but I'd like to know about the others as well.
Firstly, a code block that looks like (function(){})() is merely a function that is executed in place. Let's break it down a little.
1. (
2. function(){}
3. )
4. ()
Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help
1. function(){ .. }
2. (1)
3. 2()
You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.
An example of how it would be used.
(function(doc){
doc.location = '/';
})(document);//This is passed into the function above
As for the other questions about the plugins:
Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.
Type 2: This is again not a plugin as it does not extend the $.fn object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.
Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.
At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. What this means is that you have defined a function and you are calling it immediately.
This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal).
A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). Hence:
(function($) {
...
})(jQuery);
Which means you're passing in a reference to the actual jQuery object, but it's known as $ within the scope of the function literal.
Type 1 isn't really a plugin. You're simply assigning an object literal to jQuery.fn. Typically you assign a function to jQuery.fn as plugins are usually just functions.
Type 2 is similar to Type 1; you aren't really creating a plugin here. You're simply adding an object literal to jQuery.fn.
Type 3 is a plugin, but it's not the best or easiest way to create one.
To understand more about this, take a look at this similar question and answer. Also, this page goes into some detail about authoring plugins.
A little help:
// an anonymous function
(function () { console.log('allo') });
// a self invoked anonymous function
(function () { console.log('allo') })();
// a self invoked anonymous function with a parameter called "$"
var jQuery = 'I\'m not jQuery.';
(function ($) { console.log($) })(jQuery);
Just small addition to explanation
This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:
(function($) {
// do something
})(jQuery);
this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $.
Actually, this example helped me to understand what does (function($) {})(jQuery); mean.
Consider this:
// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4
And now consider this:
jQuery is a variable holding jQuery object.
$ is a variable
name like any other (a, $b, a$b etc.) and it doesn't have any
special meaning like in PHP.
Knowing that we can take another look at our example:
var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4
Type 3, in order to work would have to look like this:
(function($){
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
'pluginname': function(_options) {
// Put defaults inline, no need for another variable...
var options = $.extend({
'defaults': "go here..."
}, _options);
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.