Javascript-在ES5中扩展ES6类 [英] Javascript - Extend an ES6 Class in ES5

查看:69
本文介绍了Javascript-在ES5中扩展ES6类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the following code for a slider with Siema:

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

使用扩展类在幻灯片上添加点.一切正常,除了我们的网站现在使用ES6对其进行Google的移动友好测试存在问题外,因为它会显示错误消息:

Which uses extending classes to add dots to the slide. All works well except that our site is now having issues with Googles Mobile Friendly Test with it using ES6 as it gives the error:

Uncaught SyntaxError: Unexpected reserved word

在此行:

class SiemaWithDots extends Siema {

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

Is there a way I can make this compatible with 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 ,然后操纵原型以建立原型层次结构:

You would then replace the class with an old-style constructor function, and then manipulate the prototype to set up the prototype hierarchy:

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类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆