gpt4 book ai didi

Javascript - 在 ES5 中扩展 ES6 类

转载 作者:行者123 更新时间:2023-11-30 13:57:35 24 4
gpt4 key购买 nike

我将以下代码用于带有 Siema 的 slider :

https://codepen.io/pawelgrzybek/pen/boQQWy

它使用扩展类向幻灯片添加点。一切正常,除了我们的网站现在在使用 ES6 进行谷歌移动友好测试时出现问题,因为它给出了错误:

Uncaught SyntaxError: Unexpected reserved word

在这一行:

class SiemaWithDots extends Siema {

有没有办法让它与 ES5 兼容?

代码如下:

// instantiate new extended Siema
const mySiemaWithDots = new SiemaWithDots({
// on init trigger method created above
onInit: function(){
this.addDots();
this.updateDots();
},

// on change trigger method created above
onChange: function(){
this.updateDots()
},
});

// extend a Siema class by two methods
// addDots - to create a markup for dots
// updateDots - to update classes on dots on change callback
class SiemaWithDots extends Siema {

addDots() {
// create a contnier for all dots
// add a class 'dots' for styling reason
this.dots = document.createElement('div');
this.dots.classList.add('dots');

// loop through slides to create a number of dots
for(let i = 0; i < this.innerElements.length; i++) {
// create a dot
const dot = document.createElement('button');

// add a class to dot
dot.classList.add('dots__item');

// add an event handler to each of them
dot.addEventListener('click', () => {
this.goTo(i);
})

// append dot to a container for all of them
this.dots.appendChild(dot);
}

// add the container full of dots after selector
this.selector.parentNode.insertBefore(this.dots, this.selector.nextSibling);
}

updateDots() {
// loop through all dots
for(let i = 0; i < this.dots.querySelectorAll('button').length; i++) {
// if current dot matches currentSlide prop, add a class to it, remove otherwise
const addOrRemove = this.currentSlide === i ? 'add' : 'remove';
this.dots.querySelectorAll('button')[i].classList[addOrRemove]('dots__item--active');
}
}
}

最佳答案

然后,您可以将 class 替换为旧式构造函数,然后操作原型(prototype)以设置原型(prototype)层次结构:

function SiemaWithDots() {
Siema.apply(this, arguments);
}

SiemaWithDots.prototype = Object.create(Siema.prototype);
SiemaWithDots.prototype.constructor = SiemaWithDots;
SiemaWithDots.prototype.addDots = function () {
// ... your code ...
};
SiemaWithDots.prototype.updateDots = function () {
// ... your code ...
};

关于Javascript - 在 ES5 中扩展 ES6 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56942847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com