JavaScriptクラスは明示的に何かを返すべきですか?
-
29-09-2019 - |
質問
ワークフローを改善するために、Adobe Illustrator JavaScriptsをいくつか書いています。私は最近OOPを把握してきたので、オブジェクトを使用して書いていますが、コードを清潔で簡単に習得できます。しかし、私はあなたたちと一緒にいくつかのベストプラクティスをチェックしたかったのです。
(3つの推測)を作成する長方形のオブジェクトがあります...長方形。このように見えます
function rectangle(parent, coords, name, guide) {
this.top = coords[0];
this.left = coords[1];
this.width = coords[2];
this.height = coords[3];
this.parent = (parent) ? parent : doc;
var rect = this.parent.pathItems.rectangle(this.top, this.left, this.width, this.height);
rect.name = (name) ? name : "Path";
rect.guides = (guide) ? true : false;
return rect;
}
ただし、コードはそれの有無にかかわらず正常に動作します
return rect
だから私の質問は何をするかです
new rectangle(args);
明示的にそう言っていない場合は戻りますか?
私がこれを行う場合:
var myRectangle = new rectangle(args);
myRectangle.left = -100;
それはうまく機能しますi return rect
か否か。
助けてくれてありがとう。
解決
JavaScriptオブジェクトには、プロパティとメソッドのみが必要です。
メソッド内のreturnキーワードを使用します。
function rectangle(parent, coords, name, guide) {
this.top = coords[0];
this.left = coords[1];
this.width = coords[2];
this.height = coords[3];
this.parent = (parent) ? parent : doc;
this.draw = function () { // add a method to perform an action.
var rect = this.parent.pathItems.rectangle(this.top, this.left, this.width, this.height);
rect.name = (name) ? name : "Path";
rect.guides = (guide) ? true : false;
return rect;
};
}
オブジェクトの使用方法。
var myRectangle = new rectangle(args);
myRectangle.draw();
他のヒント
絶対に不要です。インスタンスが作成されると自動的に作成され、自動的に割り当てられます new
. 。戻る必要はありません this
またはそのようなもの。
厳密にoop言語で ジャワ また C ++, 、コンストラクター 何も返さないでください.
所属していません StackOverflow