Reputation: 3714
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()
?
Upvotes: 5
Views: 306
Reputation: 9026
var foo = bar.bi = function() {...};
bar.bi === function() {...} //true
foo === bar.bi //true
bar will be an object who responds to method bi.
Upvotes: 0
Reputation: 25155
It depends on where it is used.
Both foo
and bar.bi
point to same function here. That means the function can be invoked using
foo();
and
bar.bi();
At the same time it differs in the value of this
inside the function. To make the first one equal to second one, it should be invoked as given below
foo.call(bar);
or
foo.apply(bar);
This ensures that this
will point to bar
inside the function.
please refer:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply.
.
Upvotes: 0
Reputation: 83366
It's just a compound assignment
var r = x = 3;
assigns 3 to x, and also to r, which is newly declared.
Your example just substitutes a function in place of 3, and an object property—bar.bi
—in place of x
.
Upvotes: 1
Reputation: 220056
In addition to assigning the function to 2 variable, the context also changes depending on how you call it.
bar.bi();
would have it's context as the bar
object, as if you would have used this:
foo.call(bar);
But using it off the other variable, like this:
foo();
would use the context of foo
. So if foo
is in the global context, it'll be equivalent to this:
bar.bi.call(window);
Upvotes: 1
Reputation:
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
.
Upvotes: 6