Javascript 重构,遵循 DRY 方法 - 您将如何克隆传递到插件中的选项?

Javascript Refactoring, Following DRY method - How would you clone options passed into a plugin?

既然我在尝试遵循 DRY 模式,那么有人会怎么做呢? (但正确的方法)?

const lazyObj = {
  bind: 'event',
  effect: 'fadeIn',
  effectTime: 500,
  threshold: 0
}

$('.js-lazy, .js-lazy-homepage').lazy(lazyObj);

$('.js-other-lazy').lazy({
  ...lazyObj,
  beforeLoad: function() {
    $('.js-skeleton').hide();
  }
})

基本上想重写这个:

$('.js-lazy, .js-lazy-homepage').lazy({
  bind: 'event',
  effect: 'fadeIn',
  effectTime: 500,
  threshold: 0
});

$('.js-other-lazy').lazy({
  bind: 'event',
  effect: 'fadeIn',
  effectTime: 500,
  threshold: 0,
  beforeLoad: function() {
    $('.js-skeleton').hide();
  }
})

因为我使用相同的值:

{
  bind: 'event',
  effect: 'fadeIn',
  effectTime: 500,
  threshold: 0
}

您可以扩展并反对另一个。 https://api.jquery.com/jQuery.extend

var primary = {
  bind: 'event',
  effect: 'fadeIn',
  effectTime: 500,
  threshold: 0
};

var secondary = jQuery.extend(
  { beforeLoad: function() { $('.js-skeleton').hide(); } },
  primary
);

console.log(primary);
console.log(secondary);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>