What is the logic behind this:
object = object = function
I see it a lot in jQuery, for example, 1.4.4 line 99:
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
or line 332:
jQuery.extend = jQuery.fn.extend = function() {
Why would you use this syntax?
It's setting two objects to the same thing: After the statement is evaluated, both jQuery.fn and jQuery.prototype
point to the same object ( {init: function() {...}}
)
Therefore, jQuery.prototype.init and jQuery.fn.init both point to the same function (because they are both just references to the same object)
The reason jQuery uses this is just for syntactic sugar. Setting jQuery.prototype to an object makes sure that all instances of new jQuery all share the init method from their prototype. jQuery, wanting to be user friendly, creates an alias for you to add new methods to jQuery instances, that alias is jQuery.fn, also knows as $.fn
The =
assignment operator works right to left.
So first it assigns the rightmost value to the variable or property to the left of the right most =
.
Then it continues left and assigns that same value to the variable or property to the left of the next =
(again, going right to left).
From the MDC docs for assignment operator:
The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x.
Take this example:
var obj = { some:'object' }; // obj is referencing an object
var a,b; // declare a couple of variables
a = b = obj; // now all three are referencing the object referenced by "obj"
So it goes like this:
obj
is assigned a reference to { some:'object' }
b
gets assigned the value of obj
which is the reference to { some:'object' }
a
gets assigned the value of b
which is now the reference to { some:'object' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With