在 node-red 中,为什么在保存它的值后继续使用关键字 'this'?
In node-red, why continue using the keyword 'this' after saving it's value?
我正在按照教程 Creating your first node 学习如何创建我自己的 node-red 节点。如果您看下面,您会看到 this
保存在变量 node
中,以便您可以在收到 'input' 事件时发送消息。很好,但为什么要继续使用 this
来注册 'input' 事件?
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);
}
我们不能用 node.on('input', function(msg)
替换 this.on('input', function(msg)
吗?
当然可以,但我们为什么要这么做?存储 node
的唯一原因是我们可以在闭包中使用它,这就是我们将使用它的地方——而且只能在那里。请注意,还有许多 this problem 的解决方案根本不需要额外的变量。在现代代码 (ES6) 中,它们实际上更可取。
Couldn't we replace this.on('input', function(msg) with node.on('input', function(msg)?
是的,你可以。
That's fine, but why continue using this to register the 'input' event?
当您选择将 this
分配给另一个变量以便在闭包中使用时,通常有两种编码风格。
样式 #1 - 在函数顶部分配新变量,然后在函数的任何地方使用它。
样式 #2 - 仅在 this
不是所需值的闭包中使用新变量。
我在实践中都见过,所以这实际上只是您喜欢的个人风格问题。例如,here's a question 关于以 var me = this;
开头然后在函数中处处使用 me
的方法。
就我个人而言,我更喜欢样式 #2,因为我认为当您在所有可能的地方使用 this
时,代码更容易解释。
而且,当然在 ES6 环境中或从 ES6 转译时,您可以使用箭头函数来保留 this
的词法值以供在闭包中使用:
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);
}
如果你称之为 style #3,这是我的新宠,因为在 ES6 中编码是一个选项并且没有你需要的 this
的其他值在该函数中访问。
仅供参考,也可以在函数上使用 .bind()
来设置 this
的值。
我正在按照教程 Creating your first node 学习如何创建我自己的 node-red 节点。如果您看下面,您会看到 this
保存在变量 node
中,以便您可以在收到 'input' 事件时发送消息。很好,但为什么要继续使用 this
来注册 'input' 事件?
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);
}
我们不能用 node.on('input', function(msg)
替换 this.on('input', function(msg)
吗?
当然可以,但我们为什么要这么做?存储 node
的唯一原因是我们可以在闭包中使用它,这就是我们将使用它的地方——而且只能在那里。请注意,还有许多 this problem 的解决方案根本不需要额外的变量。在现代代码 (ES6) 中,它们实际上更可取。
Couldn't we replace this.on('input', function(msg) with node.on('input', function(msg)?
是的,你可以。
That's fine, but why continue using this to register the 'input' event?
当您选择将 this
分配给另一个变量以便在闭包中使用时,通常有两种编码风格。
样式 #1 - 在函数顶部分配新变量,然后在函数的任何地方使用它。
样式 #2 - 仅在 this
不是所需值的闭包中使用新变量。
我在实践中都见过,所以这实际上只是您喜欢的个人风格问题。例如,here's a question 关于以 var me = this;
开头然后在函数中处处使用 me
的方法。
就我个人而言,我更喜欢样式 #2,因为我认为当您在所有可能的地方使用 this
时,代码更容易解释。
而且,当然在 ES6 环境中或从 ES6 转译时,您可以使用箭头函数来保留 this
的词法值以供在闭包中使用:
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);
}
如果你称之为 style #3,这是我的新宠,因为在 ES6 中编码是一个选项并且没有你需要的 this
的其他值在该函数中访问。
仅供参考,也可以在函数上使用 .bind()
来设置 this
的值。