0

这可以用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++) {
...
 }
}
4

4 回答 4

2

尝试查看原型闭包

来自MDN(原型)

JavaScript 中的所有对象都是 Object 的后代;所有对象都从 Object.prototype Object.prototype 继承方法和属性, 尽管它们可能被覆盖(除了具有空原型的对象,即 Object.create(null))。例如,其他构造函数的原型会覆盖构造函数属性并提供自己的 toString 方法。对 Object 原型对象的更改会传播到所有对象,除非受这些更改影响的属性和方法沿原型链被进一步覆盖。

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

来自MDN(闭包):

Java 等语言提供了将方法声明为私有的能力,这意味着它们只能被同一类中的其他方法调用。

JavaScript 不提供执行此操作的本机方式,但可以使用闭包模拟私有方法。私有方法不仅对限制对代码的访问有用:它们还提供了一种管理全局命名空间的强大方法,防止非必要方法使代码的公共接口混乱。

于 2012-11-02T19:32:09.323 回答
1
function Sample(i, j) {
    this.ivar1 = i;
    this.ivar2 = j;

    this.emptyMethod = function() {};
}

var sample = new Sample(1, 2);

sample.ivar1; // 1
于 2012-11-02T19:31:47.640 回答
1

有多种方法可以松散地模仿这种行为。有几个库可以帮助您构建更多面向对象的 javascript,例如:

  • 原型.js
  • 骨干网.js
  • Angular.js

在一个松散的例子中使用Prototypes(不是原型框架):

function Sample() {};
var i = new Sample();
var x = new Sample();    

Sample.prototype.init = function() {
    this.ivarA = "constant 1";
    this.ivarB = "constant 2";
}
Sample.prototype.set = function(i, j) {
    this.ivar1 = i;
    this.ivar1 = j;
}

//example of override
m.set = function(i, j) {
    this.ivar1 = i + j;
    this.ivar2 = i + i + j;    
}

i.init();
i.set("hey", "whats up?");
x.set(10, 5);
于 2012-11-02T19:36:45.463 回答
1
// class Sample ...
// (including constructor)
function Sample (i, j) {

  this.ivar1 = i;
  this.ivar2 = j;

}

// ... extends Object
Sample.prototype = Object.create(Object.prototype);
// (the first Object is part of call, the second Object is the one from 'extend')

Sample.prototype.emptyMethod = function () {};
...

// Don't know where to put, probably error in original question:
// for (var i = 0; i < maxLoops; i++) {
// ...
于 2012-11-02T19:55:22.880 回答