I am making some test with extend and I got a little puzzled after some observations I made. First observations:
console.log($.extend === $.fn.extend); // trure
// and since $ === jQuery then ...
console.log(jQuery.extend === jQuery.fn.extend); // true
So far so good, isn’t it? Given the above results I then thought that doing this:
// SNIPPET 1
$.extend({
log: function(m) {
console.log(m);
}
});
and this:
// SNIPPET 2
$.fn.extend({
log: function(m) {
console.log(m);
}
});
was the same very thing. But in fact things stand in a very different way. In fact if you run SNIPPET 1 and then do:
$("body").log("whatever");
you get an error (log is not defined). But you can do:
$.log("whatever");
If you run instead SNIPPET 2 you get the opposite result, that is to say:
$("body").log("whatever"); // this will work
$.log("whatever"); // this won't
What the heck? I appreciate the fact that .extend extends the object against which it is executed ($ vs $.prototype) but what I do not get is how iit does it! Expecially given the fact that:
$.extend === $.fn.extend // true
The function is the same!! How can it produce 2 different results?
Inside the function
thiswill be different. In the first case it will be$, in the second$.fn.Have a look at the source code:
Learn more about
this.