我正在尝试将Java程序移植到Javascript。
在java中,有这些简化的类。
Source.java
public class Source {
private final int width;
private final int Height;
public Source(int width, int height) {
this.width = width;
this.height= height;
}
}
Binarizer.java
public abstract class Binarizer {
private Source source;
protected Binarizer (Source source) {
this.source = source;
}
public final int getSource() {
return source;
}
}
HistogramBinarizer.java
public class HistogramBinarizer extends Binarizer {
protected HistogramBinarizer (Source source) {
super(source);
}
public int getWidth() {
Source source = getSource();
return source.getWidth();
}
}
在javascript中,我有以下内容。
Source.js
function Source(width, height) {
this.width = width;
this.height = height;
}
Source.prototype.getWidth = function () {
return this.width;
}
Source.prototype.getHeight = function () {
return this.height;
}
Binarizer.js
function Binarizer (source) {
this.source = source;
}
Binarizer.prototype.getSource = function () {
return this.source;
}
HistogramBinarizer.js
function HistogramBinarizer (source) {
Binarizer.call(this, source);
}
HistogramBinarizer.prototype = Object.Create(Binarizer.prototype);
HistogramBinarizer.prototype.getWidth = function () {
var source = this.getSource();
return source.getWidth();
}
我的问题是,由于这些javascript“类”没有私有变量,我应该在return this.source.getWidth()
中使用HistogramBinarizer.prototype.getWidth
吗?我的目标是使移植版本尽可能接近源版本。双方有哪些优点/缺点?
我也知道创建私有变量的闭包方法,但是这个程序每秒运行几次处理实时视频流的像素,并且该方法比原型方法慢很多。
答案 0 :(得分:0)
总的来说,我建议你放弃关于保持JS设计与Java设计相同的顾虑,因为你最终会浪费大量时间来实现错误的JS设计,这将导致错误。
如果我坚持你的例子而不改变整体设计,我会继续使用吸气剂。 您的成员是否是私有的并不是使用接口而不是实现的好习惯。 特别是使用JS,您可以轻松地更改Source.java接口,最终破坏您的依赖关系。只有在JS中,你才没有像Java那样提醒你的编译器。