JavaScript 类和对象

标签 javascript

这可以用 JavaScript 完成吗?我正在将 java wiki 页面转换为 javascript。我很确定应该使用 var 而不是 int 对吗?

class Sample extends Object {

 int ivar1;
 int ivar2; 

Sample(int i, int j) {
 ivar1 = i;
 ivar2 = j;

}

int emptyMethod() {}
...

for (int i = 0; i < maxLoops; i++) {
...
 }
}

最佳答案

尝试查看 prototypes closures

来自MDN (prototypes) :

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype Object.prototype, although they may be overridden (except an Object with a null prototype, i.e. Object.create(null)). For example, other constructors' prototypes override the constructor property and provide their own toString methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

许多人都同意直接更改 Object 类型可能会导致问题,尤其是在链接其他库时。因此,通常最好使用闭包。

来自MDN (closures):

Languages such as Java provide the ability to declare methods private, meaning that they can only be called by other methods in the same class.

JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures. Private methods aren't just useful for restricting access to code: they also provide a powerful way of managing your global namespace, keeping non-essential methods from cluttering up the public interface to your code.

关于JavaScript 类和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13201805/

相关文章:

javascript - 在现有 div 上渲染 div

javascript - 如何使方法 "toString"私有(private)化?

javascript - 如何在高空照片中高效地找到地平线?

javascript - 同步 Ajax 调用 - 或 : How to wait until everything is loaded to go on?

javascript - Instafeed.js 上一个按钮

javascript - 面向对象的 Javascript 最佳实践?

javascript - 如何在js中创建返回 "hidden"数据onclick的按钮,这是用户之前输入的?

javascript - 如何将数据发布到 JsonPlaceholder 假服务器?

javascript - 如何正确地从 addStream 更新到 addTrack?

javascript - p5.j​​s 中向量数组的问题