Reputation: 3985
I have am trying to understand the Javascript/jQuery behind ColorBox. Some forms of syntax are a bit hard to search on Google as they are a bit lengthy to describe. I am having trouble understanding the following line:
publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
So I assume a new function called publicMethod is being created, but how do we but I don't really understand anything beyond the first equals symbol ("=").
A normal function declaration would look like this:
function publicMethod(options, callback) {
So if anybody could help me understanding the syntax I would greatly appreciate it.
Upvotes: 0
Views: 272
Reputation: 11322
In JavaScript, functions are on the same level as other objects - you can assign them to variables, and pass them as parameters.
Normally, you would declare a function in this way:
function SomeFunc(arg1, arg2) { /* etc etc */ }
An equivalient way would to be:
var SomeFunc = function(arg1, arg2) { /* etc, etc */ }
...because, as above, functions themselves are values that may be assigned or passed.
Many libraries will accept functions as arguments to their own functions, running the passed function at a time which suits them (or passing them on elsewhere, a la any other variable). Often this is for callbacks. When passing functions as arguments, there isn't really a need to give them a name of their own, thus the following does the job:
SomeLibrary.doSomethingThenCallback(function(arg1, arg2) {
// the doSomethingThenCallback function will decide when, if ever,
// to run this, or pass it on somewhere else, or whatever else would
// be done with any other argument value.
});
Upvotes: 1
Reputation: 943564
In:
$.fn[colorbox]
$
is an unhelpfully non-descriptive variable name. It contains an object.$.fn
access the fn
property of that object.fn[colorbox]
accesses the property of that object which a name that matches the string stored in colorbox
But the right hand side of and =
is defined first, So before it assigns that value to publicMethod
it assigns the value of $[colorbox]
to $.fn[colorbox]
.
… and before it does that it assigns (to there) a function.
function () {}
defines an anonymous function and passes it left (so it gets stored in whatever is on the other side of =
)
Upvotes: 1
Reputation: 22943
This function publicMethod(options, callback) {}
is nearly but not completely the same as var publicMethod = function(){options, callback}
. In first case you create function named publicMethod and in the second you create anonymous function and assign it to publicMethod variable. Other to assignations just save this function for the further use as API method.
Upvotes: 0