I am trying to learn the real nitty gritty details of Javascript, so I would appreciate it if someone could explain this code for me. In ColorBox, the author defines his public method as so:
publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
// do stuff...
};
Other public methods are then defined such as:
publicMethod.remove = function () {
// do more stuff
};
In practice, I know that these function can then be called as $.colorbox() and $.colorbox.remove(), but I’m a little confused by the actual syntax. Specifically, what is happening when he assigns “$.fn[colorbox]” and “$[colorbox]” to publicMethod?
Do you have any commentary on this code? Is this a good design pattern? Are there other patterns you would recommend?
In JavaScript each object is an associative array at the same time, object properties are also array keys. This means that
obj.prop = 1andobj["prop"] = 1are exactly the same thing. Also, methods are simply properties that have a function as their value. So$["colorbox"] = function() {...}creates an anonymous function and assigns it as propertycolorboxof the object$($is a regular variable name in JavaScript), this function becomes method$.colorbox()then. Note that I used the string"colorbox", your code example has it without quotation marks however – which would interpreted as a variable name, so a variablecolorboxwith the value"colorbox"is probably used there.Functions are objects as well so you can set custom properties on them. In the example the property
removeis being set on the function object and becomes its method.