0

コードを学んでいて、見つけたサンプル コードについて質問があります。

var Comment = new Schema({
    user:userStub,
    time:Date, 
    content: {type:String, required: true, trim:true}
});

OOP について学んだことから、のCommentオブジェクト インスタンスは次のSchemaように構築されると考えました。

function Schema (user, time, content){

     this.user = user;
     this.time = time;
     this.content = content;
};

var Comment = new Schema (userStub, time, content); 

代わりにCommentインスタンスを構築する利点を知っている人はいますか? var Comment = new Schema({とはどういう({意味ですか? どんな助けでも大歓迎です

4

2 に答える 2

1

この方法の利点は、署名を変更せずに関数を変更できることです。もう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);
于 2013-10-31T18:50:22.883 に答える