Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: var = var = function

I'm sure this thing is duplicated somewhere but I don't know what to search.

So, I've been looking through a Node.JS Application and found this code and wondered what it does. I have tried searching but I don't know what to search so I was hoping someone would it explain it to me.

init = refresh = function () {
    // code here..
};

I understand 1 equals, but why 2? does it make some sort of alias so that function can be run with both init and refresh?

like image 463
Aaran McGuire Avatar asked Sep 21 '13 21:09

Aaran McGuire


2 Answers

= resolves the right hand side and then assigns the result to the left hand side.

The result of doing this is the same as the result assigned.

So that assigns the function to both init and refresh

like image 183
Quentin Avatar answered Oct 03 '22 13:10

Quentin


Quentin did a very good job telling you what it is doing. I just wanted to chime in to give an example where you might use this:

Say for instance you have an object:

var obj = {
    init: function() {
        var x = this.x = [1,2,3];
    }
};

What this allows you to do is reference your x variable two different ways (either through x or this.x).

Now why would you do this? Well two major reasons.

  1. It is faster to access x rather than this.x (but you still need to access it elsewhere)
  2. It produces easier to read code when having to read/write to x lots of times in one function.

This is just another reason why you would use it.

But in most cases it is just aliases, such as: forEach -> each

like image 26
jshthornton Avatar answered Oct 03 '22 14:10

jshthornton