You've probably seen `$.fn` in jQuery source code or libraries.
WHAT DOES 'FN' IN JQUERY.FN MEAN?
To put it simply, `fn` is an alias for the `prototype` property.
JavaScript allows you to add methods to existing constructors using the `prototype` property.
Simple Prototype Example
// constructor function
var Product = function(name, price) {
this.name = name;
this.price = price;
}
var testProduct = new Product('banana', 100);
console.log( testProduct );
// result
{"name":"banana","age":100}I've created a basic constructor above. Now, let's actually add a method using the `prototype` property.
// add method
Product.prototype.getName = function() {
return this.name;
}
// add property
Product.prototype.stock = 10;As shown above, you can add new properties and methods to an existing constructor later by using the `prototype` property.
HOW TO USE $.FN
Now that we know `$.fn` is an alias for the `prototype` property, let's explain how you can actually use it.
Adding Properties to Create a Plugin
Since `$.fn` is an alias for `prototype`, you can add properties and methods just like in the example above.
Simple Plugin Example
$.fn.textRed = function() {
this.css("color", "red");
};
// surrounded by span turns red
$("span").textRed();Simple, isn't it? When actually implementing a plugin, please keep the following points in mind.
Enabling Method Chaining
// Care jQuery Method Chaining
$.fn.textRed = function(){
this.css("color", "red");
return this;
};
// What is Method Chaining?
$("span").textRed().addClass("warning");To enable method chaining, add `return this;`. This allows `addClass()` to function when appended after `textRed()`, as shown in the example above.
Anticipating Use with Other Libraries
`$` is an alias for jQuery, but it can also be used by other libraries.
Therefore, to avoid name conflicts, you should define the scope as follows:
(function ($) {
$.fn.textRed= function() {
this.css( "color", "red" );
return this;
};
}(jQuery));OTHER USES OF $.FN
・Create a single base JavaScript file (e.g., `base.js`) and load it on all pages.
・Introduce a library like FlexSlider, but only load the library on pages where it's actually used.
In the scenario above, if you write FlexSlider code in `base.js`, it will cause an error on pages where the library is not loaded.
For this reason, `$.fn` can also be used when you want to differentiate pages that have loaded a slider using a conditional statement.
if ($.fn.flexslider) {
$('.image-slider').flexslider({
});
}This code will only execute if the `flexslider` property has been added to `$.fn`.
That concludes this brief introduction to using `$.fn`.
Please understand that I've provided only a concise explanation, as going into full detail about constructors and plugins would be quite extensive.
RECOMMENDED JQUERY BOOKS
Many jQuery books are quite old. However, jQuery itself is still evolving.
📦