开发者

JavaScript Object Syntax

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.f开发者_如何学运维n.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' }


It's assigning the function to both jQuery.fn and jQuery.prototype (first example) at the same time.


This is a shortcut for

object1 = something;
object2 = object1;


The above answers all hit it, its assigning the same values to two objects. The reason why might not be so clear. The second instance is a bit easier to explain. Every member of jQuery.fn is attached to the return value of $(). So if you did the following..

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

You would get

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

Extend is a helper function that adding provided object members to the current object. jQuery uses these methods to build up its static (jQuery.getJSON) and 'dynamic' ( $('.class').load() ) methods. This gives a nice advantage of code separation during development. For example, ajax.js uses jQuery.fn.extend to add its methods of load, serialize, getScript, etc and uses jQuery.extend to add methods like jQuery.ajax

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜