この方法の利点は、署名を変更せずに関数を変更できることです。もう1つの利点は、すべてが必須ではない多くの入力パラメーターがある場合、使用していないパラメーターのデフォルト値を追加する必要がないことです... – @Michiel Reyers
以下は、コンストラクター関数のパラメーターとしてオブジェクト リテラルを使用して新しい「インスタンス」を作成し、パラメーターのリストを
削除する方法の例です。
function Schema (options) {
"use strict";
options = options || {};
this.user = options.user || "unnamed";
this.time = options.time || null;
this.content = options.content || {};
}
前のアプローチでは、エントリ パラメーターでプロパティを指定しないか、1 つまたはすべて指定することで、新しいオブジェクトを作成できます。コンストラクターの署名に加えて、変更されません。
var comment;
//no arguments
comment = new Schema();
//only one option
comment = new Schema({ user: "luis" });
//multiple options
comment = new Schema({
user: "Federico",
time: new Date(1995, 10 - 1, 31), //october 31, 1995
content: { type: Types.String, required: true, trim: true }
});
また、オブジェクトを拡張することもできるため、コンストラクター関数は、エントリ パラメーターの新しいプロパティをインスタンスに拡張することでより柔軟になります。この例では、 jQueryを使用します(タグにはありません) が、jQuery を使用せずにオブジェクトを拡張するカスタム メソッドを作成できます。
//pointer to the internal Schema
var Schema = (function () {
//cached default values
var defaults = {
user: "unnamed",
time: null,
content: {}
};
//constructor extensible
function Schema (options) {
"use strict";
//merges @options and @defaults into the instance @this
jQuery.extend(this, defaults, options);
}
//returns the reference to Schema;
return Schema;
}());
ここではConstructor パターンを使用しました。Schema
コンストラクターのシグネチャを変更することなく、 を使用して新しいプロパティを追加できます。( MODULEパターンも参照してください)。
var comment = new Schema({ user: "Felipe", age: 31 });
前のアプローチの改善点は、コンストラクター プロトタイプで既定値を設定することです。
//pointer to the internal Schema
var Schema = (function ($) {
//constructor extensible
function Schema (options) {
"use strict";
//merges @options into the instance @this
$.extend(this, options);
}
//sets the default values
Schema.prototype = {
"user": "unnamed",
"time": null,
"content": {}
};
//returns the reference to Schema;
return Schema;
}(jQuery));
var comment = new Schema();
console.log(comment);
comment = new Schema({ user: "coco", age: +"d" });
console.log(comment);