Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of var a = b.c = function(){} syntax

I've lately browsed js code and the following syntax keeps coming up:

var foo = bar.bi = function() {...}

This is unfamiliar syntax to me. Is it only to define two names for the same function? If so, why not only define it as bar.bi = function()?

like image 858
Fdr Avatar asked Jan 15 '12 18:01

Fdr


1 Answers

Assigns the same value to the variable and the bi property of the bar object at the same time.

This way the object's property gets the value, but you can still reference it as a variable, which is likely a little faster.

Effectively the same as...

bar.bi = function() {...};
var foo = bar.bi;

foo === bar.bi; // true

Or you can visualize it as...

var foo = ( bar.bi = function() {...} );

So the assignment to bar.bi happens first. The result returned from the assignment expression is the same function, and that result is assigned to foo.

like image 141
user1106925 Avatar answered Sep 24 '22 17:09

user1106925