I'm learning how to create my own node-red node by following the tutorial Creating your first node. If you take a look below, you can see that this
is saved in the variable node
so that you can send a message when an 'input' event is received. That's fine, but why continue using this
to register the 'input' event?
module.exports = function(RED) {
function LowerCaseNode(config) {
RED.nodes.createNode(this,config);
var node = this;
this.on('input', function(msg) {
msg.payload = msg.payload.toLowerCase();
node.send(msg);
});
}
RED.nodes.registerType("lower-case",LowerCaseNode);
}
Couldn't we replace this.on('input', function(msg)
with node.on('input', function(msg)
?
Couldn't we replace this.on('input', function(msg) with node.on('input', function(msg)?
Yes, you could.
That's fine, but why continue using this to register the 'input' event?
There are generally two styles of coding when you choose to assign this
to another variable so it can be used in a closure.
Style #1 - Assign the new variable at the top of the function and then use it everywhere in the function.
Style #2 - Use the new variable only in the closure where this
is not the desired value.
I've seen both in practice so it is really just a matter of personal style which you prefer. For example, here's a question about methods that start with var me = this;
and then use me
everywhere in the function.
Personally, I prefer style #2 because I think code is more self explanatory when you use this
everywhere you can.
And, of course in an ES6 environment or when transpiling from ES6, you can use an arrow function to preserve the lexical value of this
for use in the closure:
module.exports = function(RED) {
function LowerCaseNode(config) {
RED.nodes.createNode(this,config);
this.on('input', msg => {
msg.payload = msg.payload.toLowerCase();
this.send(msg);
});
}
RED.nodes.registerType("lower-case",LowerCaseNode);
}
If you call this style #3, this is my new favorite when coding in ES6 is an option and there is no other value of this
that you need access to in that function.
FYI, one could also use .bind()
on the function to set the value of this
too.