Web App Development

How does .fn work in javascript libraries?

Many javascript libraries allow you to add plugins by adding functions to their .fn field. Here's a jQuery example:

<script>
(function($){
$.fn.sayHi = function(){
$(this).html("Hello!");
};
})(jQuery)
jQuery("body").sayHi();
</script>

As you can see the object returned by the $() call implements the sayHi function. This is implemented by setting jQuery.fn to jQuery.prototype.

When you call $() a new jQuery.fn.init instance is created. And because jQuery.fn.init.prototype is set to jQuery.fn you get your new jQuery instance, including your sayHi function.

You can find the relevant code in core.js in the jQuery Github repository.

Why not just attach it to jQuery.prototype?

According to the jQuery Cookbook jQuery 1.0 used to copy the functions from jQuery.fn to the jQuery object. That proved inefficient and was therefore changed to use jQuery.prototype while maintaining backward compatibility.
I suppose this way also provides a way to disable plugins explicitly by not setting jQuery.prototype to jQuery.fn.

Comments


Follow me on Twitter
I'm building monitoring tool for site speed and Core Web Vitals.
➔ Start monitoring your website or run a free site speed test