繁体   English   中英

Java 的类概念和语法,尤其是封装和成员访问,与 Javascript 相比如何?

[英]How does the class concept and syntax, especially for encapsulation and member access, of Java compare to the one of 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.exports并使用import来访问另一个 js 文件中的类。 更多详情: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

客户端.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;

主文件

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

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

运行:节点 main.js

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM