如何覆盖传递给函数的对象中的默认参数?

时间:2017-07-31 19:14:06

标签: javascript default-parameters

创建带有一些参数的defaultOptions对象。

const defaultOptions =  {
  name: 'Adrian',
  city: 'Paris',
  job: 'Designer',
}

此函数从参数创建一个句子。

function makeSentence(defaultOptions) {
  console.log('My name is ' + defaultOptions.name + ' and I come from ' + defaultOptions.city + ' and I am a ' + defaultOptions.job + '.');
}

使用defaultOptions调用时,它会按如下方式登录到控制台:

makeSentence(defaultOptions);
// My name is Adrian and I come from Paris and I am a Designer.

我希望能够覆盖一些参数以获得如下结果:

makeSentence(defaultOptions, 'Michael');
// My name is Michael and I come from Paris and I am a Designer.

编辑:修改Patrick Roberts和Anamul Hasan的答案取得成功

defaultOptions对象保持不变。 从params创建句子的功能变为:

function makeSentence(defaultOptions) {
  var options = Object.assign({}, defaultOptions, options);
  console.log('My name is ' + options.name + ' and I come from ' + options.city + ' and I am a ' + options.job + '.');
}

覆盖默认参数:

makeSentence({name: 'Michael'}); // overrides only the name attr. 

3 个答案:

答案 0 :(得分:3)

这应该有效。这不会覆盖defaultOptions,而是复制值并替换它。

container.Register(c => new AppointmentHandlers(
     new AppointmentHandler1(),
     new AppointmentHandler2());

答案 1 :(得分:2)

您可以使用ES6默认参数执行此操作:



const defaultOptions = {
  name: 'Adrian',
  city: 'Paris',
  job: 'Designer'
}

const makeSentence = function makeSentence(name = this.name, city = this.city, job = this.job) {
  console.log('My name is ' + name + ' and I come from ' + city + ' and I am a ' + job + '.')
}.bind(defaultOptions)

makeSentence()
makeSentence('Michael')
makeSentence('Michael', 'London')
makeSentence('Michael', 'London', 'Programmer')




但是,我认为这样做会更直观,几乎就像默认的命名参数一样:



const defaultOptions = {
  name: 'Adrian',
  city: 'Paris',
  job: 'Designer'
}

const makeSentence = function makeSentence({ name = this.name, city = this.city, job = this.job } = {}) {
  console.log('My name is ' + name + ' and I come from ' + city + ' and I am a ' + job + '.')
}.bind(defaultOptions)

makeSentence()
makeSentence({ name: 'Michael' })
makeSentence({ name: 'Michael', city: 'London' })
makeSentence({ name: 'Michael', city: 'London', job: 'Programmer' })




答案 2 :(得分:0)

 function makeSentence(defaultOptions, nameOverride) {
   defaultOptions.name = nameOverride || defaultOptions.name;
   console.log('My name is ' + defaultOptions.name + ' and I come from ' + defaultOptions.city + ' and I am a ' + defaultOptions.job + '.');
 }

如果你想让它更有活力:

 function makeSentence(defaultOptions, property, nameOverride) {

   defaultOptions[property] = nameOverride || defaultOptions[property];
   console.log('My name is ' + defaultOptions.name + ' and I come from ' + defaultOptions.city + ' and I am a ' + defaultOptions.job + '.');
 }

 makeSentence(defaultOptions, 'name', 'Micheal');