I have a code snippet I came across when learning jQuery. I am familiar with jQuery's basic selector syntax $('element'), but I do not know what the $. syntax means and here is an example of it. Could someone explain the 1st and 4th lines in depth please?
var $ = function(a) {
alert(a);
}
$.add = function(a,b) {
return a + b;
}
More specifically how can you declare a variable with just $ in the 1st line and what does $.add mean.
Thanks a bunch!
This is based on a post I found JQuery $. meaning
Reading the comments I see the key misunderstanding is that I didnt know you can have a $ and it doesnt necessarily refer to jquery. Im sorry for not knowing any better, but I dont see the need for several downvotes on my first ever post.
For first you can think about $ as another valid name for Javascript variable.
As you know functions in Javascript are callable objects. You can have additional properties and functions defined in the function object. In your case you have a reference with name $ to a function. $.add - and this adds a new property into the object $ with name add which refers to another function
Related
This question already has answers here:
Why does JQuery have dollar signs everywhere?
(7 answers)
Closed 9 years ago.
I've got some code that works fine - I adapted it from something else (this is the simplified version, not production, of course):
$(".colorMe td").each(function() {
var val = (this.innerHTML);
if (val == "Yes") {
this.style.backgroundColor = "#F00000";
}
});
See also http://jsfiddle.net/GAwrB/221/
I don't know what the $ means though. I've seen lost of other posts saying that it might have something to do with jQuery, but I can't find any definitive answer. I'm sure that other newbies like me would find it useful to know.
Edit:
This question is different from Why does JQuery have dollar signs everywhere? as I initially didn't know that the $ meant jQuery - so the previous question isn't useful for anyone like me, who'd new to javascript.
I also see that there are basically two different answers given - some say that $ is a variable name, while others say that it calls jQuery - look to me that the jQuery answer is right here - in which case, I don't understand why some people say that it's a variable name - I assume that that's right in some cases.
Short answer: it's impossible to tell. $ is just another valid variable name, you'll need to look elsewhere to see what other Javascript is included which might be defining that function.
By the context, it's probably jQuery, but you'll be only able to tell for sure by seeing whether jQuery is being included on the page.
You might as well ask "What does foo mean in this code?"
$ is a variable name. It has no special meaning in JavaScript.
A number of libraries (such as MooTools, Prototype.js, Zepto and jQuery) assign a function to it. Since it is followed by (arguments) it is a function (or an error!).
Since the return value of that function is an object with an each method, and that jQuery is ludicrously popular, it is probably jQuery.
It's jQuery. It's used to refer to an object with the given attributes. i.e.: $(".a").click(); is invoking click for an object with class name "a" (the dot is class name, has tag is ID).
I'd like to know exactly what's going on here. I know what $(document).ready(function() {...}); does and when it comes into effect. Same goes for jQuery(function($) {...}.
But what does this do?
!function ($) {
$(function(){
var $window = $(window)
//normal jquery stuff
})
}(window.jQuery)
Is it loaded when jQuery is loaded instead of when the document is 'ready'?
It creates a closure in which the variable $ is assigned the value of window.jQuery.
The intention is to allow the uninformatively named variable $ to be used as a shortcut for jQuery without conflicting with the large number of other libraries and custom functions that also use $ as a variable name.
Using the ! operator before the function causes it to be treated as an expression
!function () {}()
The syntax you're looking at is used for setting up a jQuery closure. This is used to ensure that the jQuery $ variable is garuanteed to be available and correct within the code; ie it can't be overwritten in the global scope by anything else (which is possible if you're using multiple libraries, etc).
This technique is often used by jQuery plugin authors -- if you're interested in finding out more, the docs are here, and explain in more detail why you'd want to wrap your jQuery code in a function like this.
The only point of interest that's different in your example is that in the docs, the function is wrapped in brackets, whereas in the example you've given it's preceded by a !
The ! is a not operator, but doesn't actually get used for anything; I think it's just there instead of the brackets to save a single character of code. Probably helpful if you're into minifying javascript.
Not quite sure but I guess this is somewhat equivalent to (function(){})() approach and it's about js closures. And it ensures $ and jQuery are the same thing
The '!' is a 'not' operator. It doesn't do anything in the code. The only reason it is there is to signify that the function will execute immediately.
You may also see functions wrapped in parenthesis instead.
(function() {}());
Whatever is used is personal preference.
$.each(data, function(i){
_(catalog.add(this));//iterating through each object in objectStore
});
I was wondering what difference does it make if i exclude the underscore before the function call.
Update
The OP is referring to the jquery indexeddb plugin.
It calls a function called _ and passes the result of the expression catalog.add(this) as the first and only argument.
That function is quite likely the one defined by the library you can download from underscorejs.org, which is another in a series of libraries that lack intention revealing variable names.
http://underscorejs.org/#chaining
I'm not exactly sure what its doing for you, but here's the doc.
EDIT:
Short answer: Yes, no different. Remove it.
From your source js file, _ is a function name for logging result of promise object. So you have to remove it in production code if you don't care what add method return. add method should return newly created keys.
To me, those $, i, _ and this does not make sense.
add(this) is very scary. what is this?
Lines 10 - 16 of jquery.effects.core.js:
;jQuery.effects || (function($, undefined) {
var backCompat = $.uiBackCompat !== false; // Irrelevant
$.effects = {
effect: {}
};
})(jQuery); // At end of file
As I understand it, this adds an effects "namespace", but only if it doesn't already exist.
Can someone explain to me:
What is the initial semi-colon for?
What is the purpose of the undefined parameter? Is the meaning of undefined overridden in some way?
What's the difference between adding a function directly to the jQuery object, and adding one to jQuery.fn as recommended in the jQuery documentation?
Finally, if I wanted to create a bunch of jQuery plugins that would only be used by my own team, would it make sense to lump them all under a company namespace using something like the code above?
Edit: I realize now jQuery.effects is probably a bad example. I see jQuery.ui.core.js does it differently:
(function( $, undefined ) {
$.ui = $.ui || {};
// add some stuff to $.ui here
$.fn.extend({
// plugins go here
});
})(jQuery);
But what is the use of the ui object if plugins are added directly to $.fn anyway? Could I define my namespace under $.fn and add all my plugins to $.fn.acme, so that I use them like so: $('something').acme.doStuff()?
Is there a best practice for this sort of thing?
It checks if jQuery.effects exists
If not, it defines a function and calls in the same time
(function() { ... } (jquery), it passes jQuery object for reasons related to scope and conflict and such.
The first line in that function is said to be irrelevant, it seems to be checking a presence of a jQuery plugin property
It defines a placeholder (like namespace or container class) for the effects jQuery plugin property.
So, to your questions:
1 . What is the initial semi-colon for?
I think nothing special. Just ensuring clean statement. This has some edge cases if the last line before this one was a function declaration close.
2 . What is the purpose of the undefined parameter? Is the meaning of undefined overridden in some way?
It just ensures this doesn't happen later. Passes the global object directly. Common pattern I think.
3 . What's the difference between adding a function directly to the jQuery object, and adding one to jQuery.fn as recommended in the jQuery documentation?
It's the way jQuery is structured and general organization issue. The jQuery object is a function and returns an object. The .fn handles registering this one to apply on returned jQuery objects (from jQuery select or so), so, that's better so that jQuery actually knows about your added function.
4 . Finally, if I wanted to create a bunch of jQuery plugins that would only be used by my own team, would it make sense to lump them all under a company namespace using something like the code above?
Most people don't do it. Wouldn't recommend it. Maybe a common "small" prefix is enough.
I have been wondering how I can create functions like jQuery. For example: $(ID).function()
Where ID is the id of an HTML element, $ is a function that return the document.getElementById reference of the element "ID" and function is a custom javascript function.
I'm creating a little library which implements some functions. And I want to use that sintax without using jQuery.
Now, my questions are: how I can implement that? What is the name of the tecnique that allow that?
Edit:
What I want to do is this:
HTMLElement.prototype.alertMe = function() {alert(this.value);}
Then, when I call document.getElementById('html_input_id').alertMe(), it must show an alertbox with the input value. But HTMLElement.prototype doesn't work in IE.
$ = function(id) {
return document.getElementById(id);
}
Okay, look, what you're asking has a lot of details and implications. The code for jQuery is open source, you can read it for the details; you'd do well to find a good Javascript book as well, the the O'Reilly Definitive Guide.
$ is just a character for names in JS, so as some of the other answers have shown, there's no reason you can't just write a function with that name:
var $ = function(args){...}
Since everyone and his brother uses that trick, you want to have a longer name as well, so you can mix things.
var EstebansLibrary = function(args){...}
var $ = EstebansLibrary; // make an alias
Since you end up doing different things with the entry point function, you need to know how JS uses arguments -- look up the arguments object.
You'll want to package this so that your internals don't pollute the namespace; you'll want some variant of the module pattern, which will make it something like
var EstebansLibrary = (function(){
// process the arguments object
// do stuff
return {
opname : implementation,...
}
})();
And you'll eventually want to be prepared for inheritance and that means putting those functions into the prototype object.
You can use prototype to assign a new function to the Element prototype.
Element.prototype.testFunction=function(str){alert(str)};
This would provide the function 'testFunction' to all HTML elements.
You can extend any base Object this way, i.e. Array, String etc.
This will work without any plugin at all - although that said I don't think it will work in IE. I believe libraries such as MooTools and jQquery create their own inheritance with DOM elements to ensure cross-browser compatibility, although don't quote me on that.