2017-04-18 13 views
1

ForInを実行してコンストラクタの設定をマージできないのはなぜですか?ForInを使用してオブジェクトの設定をマージする

私はこの小さなクラスにオープンな構成があるので、コードを短縮するためにForInを実行するだけです。

は、基本的にはこの

var FormMessage = (function() { 
    ... 
    function FormMessage(args) { 
     for (var attr in args) { this.Conf[attr] = args[attr]; } 
    } 
    ... 

    return FormMessage; 
})(); 

var i = new FormMessage({mobile: true, form:{selector: '.the-first'}}), 
    e = new FormMessage({mobile: false, form:{selector: '.the-second'}}); 

にこの

var FormMessage = (function() { 

    ... 

    function FormMessage(args) { 
     this.Conf = { 
      mobile:args.mobile || Configurations.mobile, 
      form: { 
       selector: args.form.selector || Configurations.formSelector 
      }, 
      ... 
     } 
    } 
    ... 
    return FormMessage; 
})(); 

var i = new FormMessage({mobile: true, form:{selector: '.the-first'}}), 
    e = new FormMessage({mobile: false, form:{selector: '.the-second'}}); 

を回すしかし、私はこの後、第2の時間を行う場合、私は、オブジェクトを初期化するためには、最初のものを上書きします。

私はこの作業をどのように行うことができますか?

ありがとうございました。

+0

すべてのプロパティはオプションで、初期化時に渡されない場合は、何かをデフォルトにする必要があり、単一のオブジェクトであると仮定される番号 – Kup

答えて

0

おそらく次のようなコードに沿っていますか?私はまた、IIFEは不要だと思っています。

function FormMessage(conf, args) { 
 
    Object.keys(args).forEach(e => conf[e] = args[e]); 
 
    return Object.assign({}, conf); // returns a fresh new object 
 
} 
 
// initial config object 
 
var confObj = {mobile: 'wow'}; 
 
var i = new FormMessage(confObj, {mobile: true, form:{selector: '.the-first'}}), 
 
    e = new FormMessage(confObj, {mobile: false, form:{selector: '.the-second'}}); 
 

 
console.log(i, e);

関連する問題