我必须使用“this”来处理NodeJs中的“object”属性吗?

我正在从Java切换到NodeJs,所以有些东西对我来说依然模糊。

我正在尝试使用脚本来处理Java中的类。 我知道这是做到这一点的方法:

var client = require('scp2'); var host, username, password; var SftpHandler = function (host, username, password) { this.host = host; this.username = username; this.password = password; }; SftpHandler.prototype.downloadFile = function (path, callback) { console.log(this.host,username,password,path); }; module.exports = SftpHandler; 

问题是当我从这样的另一个脚本调用它:

 var sftpHandler = new SftpHandler(credentials.sftpHost, credentials.sftpUsername, credentials.sftpPassword); sftpHandler.downloadFile(credentials.sftpPathToImportFiles+configFile.importFileName, callback); 

我有162.*.*.* undefined undefined undefined ...在控制台日志中。

我意识到这是由于我缺乏this. 在我所指的对象属性中。 但为什么呢this. 需要? 这是正确的做法吗?

有时在Java和JavaScript之间映射概念有点棘手。

简单的回答是,如果您要尝试在JavaScript中使用Java中的类实例,那么您每次都需要调用“this”。

原因在于JS中的this实际上是一个特殊的局部作用域variables,它指向调用作用域。 不一定总是实际的类实例,信不信由你,所以你需要更详细地阅读它。

许多人select不去尝试,因为有一些地方遵循Java成语会让你陷入困境,否则就是让事情变得更加困难/复杂/难以维护。

但在任何情况下,作为一个例子,如果this可以改变,如果你的downloadFile方法需要提供一个嵌套函数,例如你想用一个匿名函数来处理callback:

 SftpHandler.prototype.downloadFile = function (path, callback) { console.log(this.host); // this here refers to your object instance fileManager.getFile(path, function(e, file){ console.log(this.host); // 'this' here refers to the anonymous function, not your object }) }; 

希望有所帮助。

**编辑如何进入这个callback里面**

有几个方法来保持参考。 将范围内的另一个variables设置为原始值是非常常见的,如下所示:

 SftpHandler.prototype.downloadFile = function (path, callback) { console.log(this.host); // this here refers to your object instance var self = this; fileManager.getFile(path, function(e, file){ console.log(this.host); // 'this' here refers to the anonymous function, not your object console.log(self.host); // 'self' there refers to the enclosing method's 'this' }) }; 

其他人更喜欢使用函数#绑定更明确:

 SftpHandler.prototype.downloadFile = function (path, callback) { console.log(this.host); // this here refers to your object instance fileManager.getFile(path, function(e, file){ console.log(this.host); // 'this' here refers to the your object thanks to bind() }.bind(this)); }; 

为了避免使用这个,你的模块可以是一个返回对象的函数:

 var client = require('scp2'); var SftpHandler = function (host, username, password) { return { downloadFile: downloadFile }; function downloadFile (path, callback) { console.log(host, username, password,path); } }; module.exports = SftpHandler; 

然后你不用新的就调用这个函数:

 var sftpHandler = SftpHandler(credentials.sftpHost, credentials.sftpUsername, credentials.sftpPassword); sftpHandler.downloadFile(credentials.sftpPathToImportFiles+configFile.importFileName, callback);