i find it everywhere, like this.
function($) {
开发者_如何转开发$.test = { some code }
}
what does it mean?
Think of $
just like any other variable. For jQuery, it's the jQuery object, which is pretty powerful. But it's just like any other variable; you could write your own $
if you wanted to, for example.
It's an unusual variable name, yes, but there's nothing magical about it. The .something
is just a property of the variable $
. It's no different than writing obj.something
, except the variable name is $
instead.
The other non-alphanumeric character you can use in JavaScript as a variable name is _
(the underscore). It's used in some other libraries, like underscore.js . But again, there's nothing special about using _
.
You should think about jQuery code as a division between two ways of calling functions:
- Methods on selections. This is the standard "find some elements, do something with them" technique. It's code like
$('p').val()
,$('div').prepend()
, etc. - Methods without selections. These are functions that don't require you to do a selection before calling a function. These are functions like
$.ajax
,$.param
,$.each
. For the sake of convenience, they are properties of the global variable$
, which is the jQuery library. Often, they aren't jQuery-specific, but are useful pieces of code to include in the library.
the $ variable is an alias to the jQuery object / 'namespace'. So you when you see $.function()
you are actually calling a method named 'function' on the jQuery object. In your example code provided an object named test
is being attached to the jQuery object. if you wrote $.test = function() { }
you would be attaching a function (method) instead of an object.
Go read the jQuery API and tutorials on their websites.
In particular "How it works" and "Plugin Authoring". As your code sample looks like a jQuery plugin
精彩评论