这可以用 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
类型可能会导致问题,尤其是在链接其他库时。因此,通常最好使用闭包。
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/