Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Object Syntax

Tags:

javascript

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?

like image 333
Sam Avatar asked Dec 21 '22 18:12

Sam


2 Answers

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

like image 54
Juan Mendes Avatar answered Dec 24 '22 08:12

Juan Mendes


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' }

like image 27
user113716 Avatar answered Dec 24 '22 09:12

user113716