Java的类概念和语法特别是用于封装和成员访问与Javascript相比如何?

问题描述

我对Java有很多了解,但是我绝对不熟悉Javascript。我知道有关语言本身的一些背景信息,仅此而已。现在我正在使用某个API,因此我需要Js。所以我下载了Node.js并开始编写一些代码。我意识到Java与众不同,但没有找到任何好的解决方案。这是一个示例:

public class Client {

private String username;
private String password;
private String host;
private final int port = 25565;

public Client(String username,String password,String host) {
    this.username = username;
    this.password = password;
    this.host = host;
}

public String getUsername() {
    return username;
}

public int getPort() {
    return port;
}

public String getPassword() {
    return password;
}

public String getHost() {
    return host;
}
}

这是oop的常规Java类。有人可以给我一个例子,如何在Js中创建类似的东西,以及如何在js中访问这样的类/文件吗?

解决方法

我不会给出与sami相同的答案,但是还有另一种在JS中创建类的方法,该方法确实允许仅父级可以访问的变量:

function Client(username,passwd,host) {
    const port = 25565; //this is private

    this.getUsername = () => username;  //this is public
    this.getPort = () => port;
    this.getPassword = () => passwd;
    this.getHost = () => host;
}

var client = new Client("john doe","pass","www.example.com");
client.getUsername();   //returns "john doe"

在JS中,类不过是函数。类的成员函数是闭包。还要注意,代码的简洁性归功于箭头函数,并且Client构造函数的参数对于该范围内的闭包而言是可访问的。您也可以修改它们的值,就像在此范围内用letvar声明它们一样。

,

在Nodejs中,您可以创建一个类,该类继承自JAVA。但是,nodejs没有变量类型或公共/私有方法。为了方便起见,在变量名中添加_代表私有变量。

要访问js文件,请使用module.exports和类名。 使用require访问另一个js文件中的类。

如果您使用es6 babel来安装package.json。您可以直接使用export default代替module.exportsimport用于访问另一个js文件中的类。更多详细信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

client.js

class Client {
   port = 25565;
   constructor(username,password,host) {
      this._username = username;
      this._password = password;
      this._host = host;
   }

   getUsername() {return this._username}

   getPort() {return this.port}

   getPassword() {return this._password}

   getHost() {return this._host}
}

module.exports = Client;

main.js

var Client = require('./client.js');

console.log(new Client('pr','password','2020'))

运行:节点main.js

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...