views:

301

answers:

4

I see in jQuery something like this:

jQuery.fn = jQuery.prototype = {}

Why is this being done? Isn't this the same thing just saying jQuery.prototype = {}? I'm not sure I understand what Resig is accomplishing here.

+11  A: 

The same as:

jQuery.prototype = {}
jQuery.fn = jQuery.prototype

In my opinion having all in one line makes more clear that your assigning the same value to both variables

victor hugo
Thanks a lot. That really clears it up.
+1  A: 

The statement x = a = {} means that {} is assigned to a that is assigned to x. So it’s equal to a = {}; x = a.

Gumbo
Yes but in his example jQuery.fn is already the same entity as jQuery as jQuery.prototype. The fn is just a shortcut for prototype.
amischiefr
+2  A: 

One thing to know is that in javascript, every expression has a return value, regardless of if it has any side effects (of assignment)

From right to left, you have the following statements:

(jQuery.fn = (jQuery.prototype = ({})))

Evaluating the first part gives an empty object: {}:

(jQuery.fn = (jQuery.prototype = {}))

The second statement executes and sets jQuery.prototype to {}, and it evaluates to jQuery.prototype, giving the second part:

(jQuery.fn = jQuery.prototype)

which sets jQuery.fn to jQuery.prototype, which then evaluates to:

jQuery.fn

which does nothing.

FryGuy
Evaluating the first part yields an empty object (not an 'array')--that can be an important distinction.
steamer25
Actually is jQuery.fn = jQuery.prototype, not jQuery.fn = {}, as jQuery.fn and jQuery.prototype are supposed to be aliased.
Chris Jester-Young
in javascript land aren't arrays/tables/objects the same thing? It's been a while. Regardless, I've updated my answer.
FryGuy
They are essentially the same, but arrays have special behavior for numeric properties (basically, length gets adjusted automatically when you assign to a numeric index that doesn't exist). Arrays also have a separate prototype, which is where they get slice, map, sort, etc.
Matthew Crumley
+3  A: 

This is equivalent to:

jQuery.prototype = {}
jQuery.fn = jQuery.prototype

In other words jQuery.fn and jQuery.prototype both point to the same object.

Kevin Loney