我需要创建几个滑块实例。每个滑块有两个参数:一个元素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})
// ...但我不知道怎么做才是正确的
发布于 2018-07-06 20:00:28
您可以使用...创建一个包含options的新对象,其中包含一个附加的键speed。
new Swiper ('#swiper1', {...options, speed: 500})发布于 2018-07-06 20:00:51
你只是错过了扩展操作符:
var swiper1 = new Swiper ('#swiper1', {...options, speed: 500})它将将options的所有属性复制到传递给Swiper构造函数的对象文本中。
发布于 2018-07-06 19:59:11
使用Object.assign()有选择地克隆和覆盖属性。
扩展语法也有效,我会告诉您使用它,但如果您现在可能担心边缘和Safari支持:在对象文本兼容表中扩展
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}));
https://stackoverflow.com/questions/51216868
复制相似问题