[英]How to rewrite js to java, (instanceof usage, replace overload)?
假設我們在js中有這樣的function
this.add = function (x, y) {
if (x instanceof Vector2d) {
this.x += x.x;
this.y += x.y;
return this;
}
this.x += x;
this.y += y;
return this;
};
我是否必須在 java 中重載它,就像:
public Vector2D add(Vector2D other) {
this.x += other.x;
this.y += other.y;
return new Vector2D(this.x, this.y);
}
public Vector2D add(double number) {
this.x += number;
this.y += number;
return new Vector2D(this.x, this.y);
}
或者有沒有更好/更智能/緊湊的方法來做這些事情?
public class Vector2D {
private double x;
private double y;
//...
public Vector2D add(Vector2D other) {
this.x += other.x;
this.y += other.y;
return this;
}
public Vector2D add(double x, double y) {
this.x += x;
this.y += y;
return this;
}
//...
}
您可以在每次調用該方法時返回this
而不是創建一個新的Vector2D
object,就像您在 js 版本中所做的那樣。
但我覺得這類問題更適合代碼審查社區: https://codereview.stackexchange.com
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.