JavaScript object syntax

What is the logic behind this:

object = object = function

I see this 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?

+4
source share
5 answers

It sets two objects to the same thing: after evaluating the expression, both jQuery.fn and jQuery.prototype specify the same object ( {init: function() {...}} )

Therefore, jQuery.prototype.init and jQuery.fn.init point to the same function (because they are both references to the same object)

The reason for using jQuery is only in syntactic sugar. Setting jQuery.prototype for an object ensures that all instances of the new jQuery will 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, this alias jQuery.fn is also known as $ .fn

+4
source

Assignment operator = works from right to left.

So, first he assigns the rightmost value to the variable or property to the left of the right side = .

Then it continues to the left and assigns this value to a variable or property to the left of the next = (again, moving from right to left).

From the MDC docs for the assignment operator :

The main assignment operator is (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y 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 looks like this:

  • obj assigned a link to { some:'object' }

  • b gets the value obj , which is a reference to { some:'object' }

  • a gets the value of b , which is now a reference to { some:'object' }

+3
source

It simultaneously assigns a function to both jQuery.fn and jQuery.prototype (first example).

+2
source

This is a shortcut for

 object1 = something; object2 = object1; 
+1
source

The above answers hit everything by assigning the same values ​​to two objects. The reason this may not be so clear. The second example is a little easier to explain. Each jQuery.fn member is associated with a return value of $ (). So, if you have done the following.

 jQuery.fn.myFunc = function() { return 'blah'; } 

You'll get

 $('#blah').myFunc(); // returns 'blah' 

Extend is a helper function that adds the provided object elements to the current object. jQuery uses these methods to create its own static ( jQuery.getJSON ) and "dynamic" ( $('.class').load() ) methods. This gives a good advantage of code separation during development. For example, ajax.js uses jQuery.fn.extend to add its loading methods, serialization, getScript, etc. And uses jQuery.extend to add methods like jQuery.ajax

+1
source

Source: https://habr.com/ru/post/1336832/


All Articles