2

I realize that one is a prototype can someone tell me the difference between these two?

$.addMessage = function () { 

and

$.fn.addMessage = function () {

From what I can see one extends JQuery and the other JQueryStatic in typescript

interface JQuery {
    addMessage();
}

interface JQueryStatic {
  addMessage();
}
  • Possible duplicate of [What does jQuery.fn mean?](http://stackoverflow.com/questions/4083351/what-does-jquery-fn-mean) – John Dvorak Oct 29 '12 at 07:45
  • @Jan - Thanks for the link? Can you show me where in the link you nominated as a duplicate does it explain the difference between the two ways to declare a function. –  Oct 29 '12 at 07:55
  • I said 'possible'. The other answer is sufficient if you understand the Javascript object model. – John Dvorak Oct 29 '12 at 08:00

1 Answers1

4

If you add a function as

$.addMessage = function(){

you can later access the function as

$.addMessage()

Semantically, the function has no relation to specific jQuery instances, and may be regarded to as an equivalent of a static method (belongs to a class) in Java.


If you add a function as

$.fn.addMessage = function(){

Since jQuery defines $.fn as an alias to $.prototype, this is equivalent to

$.prototype.addMessage = function(){

Javascript automatically assigns Class.prototype as a prototype of the objects created with new Class(). $(...) uses new $(...) internally, meaning it does create new objects with $ as the constructor. This means that $.fn.addMessage can also be accessed as

$(".messageContainer").addMessage()

Semantically, $.fn.addMessage is related to specific jQuery instances. It means that this inside the addMessage function does not refer to $.fn, but rather to $(...). $.fn may thus be regarded to as an equivalent of an instance method (belongs to an instance) in Java.


In other words, if you declare your function as

$.addMessage = function(){ 

, you use it as

$.addMessage()

If you declare it your function as

$.fn.addMessage = function(){

, you use it as

$(".messageContainer").addMessage()
John Dvorak
  • 26,799
  • 13
  • 69
  • 83