向函数内的对象添加值

时间:2018-07-06 19:56:53

标签: javascript object

我需要创建一个滑块的多个实例。每个滑块都有两个参数:一个元素ID和一个包含不同选项的对象。除了一个选项(以下示例中的速度)之外,所有滑块的所有选项都相同。

var swiper1 = new Swiper ('#swiper1', {
    width: 200,
    distance: 10,
    slides: 5,
    preventClick: true
    // ... many others options
    speed: 300 
});

var swiper2 = new Swiper ('#swiper2', {
    width: 200,
    distance: 10,
    slides: 5,
    preventClick: true
    // ... many others options
    speed: 500 
});

// ... many others instances of Swiper

因此,为了减少代码的长度并避免多次复制/粘贴,我可以这样做:

var options = {
    width: 200,
    distance: 10,
    slides: 5,
    preventClick: true
    // ... many others options
    speed: 500 
}

var swiper1 = new Swiper ('#swiper1', options)
var swiper2 = new Swiper ('#swiper2', options)
var swiper3 = new Swiper ('#swiper3', options)
// ...

但是正如我提到的,一个实例与另一个实例之间只有一个参数不同,因此我需要执行以下操作:

var options = {
    width: 200,
    distance: 10,
    slides: 5,
    preventClick: true
    // ... many others options
}

var swiper1 = new Swiper ('#swiper1', {options, speed: 500})
var swiper2 = new Swiper ('#swiper2', {options, speed: 700})
var swiper3 = new Swiper ('#swiper3', {options, speed: 300})
// ...

但是我不知道正确的方法是什么

3 个答案:

答案 0 :(得分:5)

您可以使用...创建一个包含options并带有附加键speed的新对象:

new Swiper ('#swiper1', {...options, speed: 500})

答案 1 :(得分:4)

您只是想念点差运算符:

var swiper1 = new Swiper ('#swiper1', {...options, speed: 500})

这会将options的所有属性复制到传递给Swiper构造函数的对象文字中。

答案 2 :(得分:2)

使用Object.assign()选择性地克隆和覆盖属性。

spread语法也能正常工作,我会告诉您使用它,但是如果您现在可能担心Edge和Safari支持:Spread in object literals compatibility table

class Swiper {
  constructor(el, kwargs) {
    console.log(kwargs.speed);
  }
}

var options = {
  width: 200,
  distance: 10,
  slides: 5,
  preventClick: true
}

var swiper1 = new Swiper('#swiper1', Object.assign({}, options, {speed: 500}));
var swiper2 = new Swiper('#swiper1', Object.assign({}, options, {speed: 700}));
var swiper3 = new Swiper('#swiper1', Object.assign({}, options, {speed: 300}));