Hi guys,
have just joined the team and am very happy to be contributing to the HiFi streamer that I now use on two rooms in my flat!
I wanted to open a discussion about something I see throughout the Volumio source code that I think could do with changing (possibly). I thought it might be a fun discussion
BTW I am not a javascript expert in anyway, but think I know about this bit.
In nearly all the source code, at the top of every method, a reference called âselfâ is made that points to âthisâ. The âselfâ reference is then used exclusively to reference the current object. Most of the time this âselfâ reference is entirely unnecessary and actually makes the code harder to read.
The only time you actually need to do this is when you wish the âthisâ in an outer scope to be available at runtime in an inner scope that you are declaring - e.g. (in pseudocode)
This does not work
[code]function A() {
console.log(this); // resolves now to A
this.onSomeEvent = function() {
console.log(this); // resolves later to the function not A
}
}[/code]
This âthisâ inside the function is lexically scoped at runtime to the function itself.
In normal javascript this is worked around by creating a âselfâ reference to âthisâ before defining the function
[code]function A() {
console.log(this); // resolves now to A
var self=this;
this.onSomeEvent = function() {
console.log(self); // resolves later to A
}
}[/code]
As far as I am aware this is the only time you need to create a reference to âthisâ, otherwise you can use this quite safely.
The problem I have is that creating a âselfâ reference implies you are going to use it in a callback later, but most of the time that is not happening - it makes the code harder to understand. Only using âselfâ when it is required will make it clearer what was intended (i.e. we are going to us this in a callback).
The latest version of the alsa controller index.js is coded in this style (I just updated it).
github.com/volumio/Volumio2/blo ⌠r/index.js
You can see only one reference to âselfâ is needed for the client callback.
What do you all think?