首页 > 一个JS轮播报错

一个JS轮播报错

写了个面向对象轮播,实例化后默认执行这个defaultRunning()方法,执行正常,鼠标移动到对象上也正常停止播放,但当鼠标离开后,开始报错,似乎this的指向变了,目前没搞明白,麻烦大家给看看,谢谢

报错提示:

程序部分代码:

function Plays(){
    //代码略
}

Plays.prototype = {
    defaultRunning: function(){
        //默认执行的方法
        this.play();
        
        //鼠标移动上去停止播放
        this.obj.onmouseover = this.stop;

        //鼠标离开后继续播放
        this.obj.onmouseout = this.play;
    },
    prevPage: function(){
        //上一个

    },
    nextPage: function(){
        //下一个
        console.log("nextPage执行的代码");

    },
    play: function(){
        //默认定时执行
        var _this = this;
        timer = setInterval(function(){
            _this.nextPage(); //报错的位置
        },1000);

    },
    stop: function(){
        clearInterval(timer);
    }
}

new Plays(). defaultRunning();

調整了您的範例如下 Codepen 範例

function Plays(selector) {
  this.page = 0;
  this.element = document.querySelector(selector);
}

Plays.prototype = {
  defaultRunning: function() {
    this.play();
    this.element.onmouseover = () => this.stop(); // 應該使用閉包
    this.element.onmouseout = () => this.play();
  },
  prev: function() { },
  next: function() {
    this.element.innerHTML = ++this.page;
  },
  play: function() {
    this.timer = setInterval(function() {
      this.next();
    }.bind(this), 1000);
  },
  stop: function() {
    clearInterval(this.timer);
  }
}

new Plays('.slide').defaultRunning();

this.obj.onmouseover = this.stop;
this.obj.onmouseout = this.play;

onmouseover, 如果你没有做过特殊处理的话, 回调函数中的 this 指向的是你的obj,所以说,this的确会变得。

可以尝试改成:

this.obj.onmouseover = this.stop.bind(this);
this.obj.onmouseout = this.play.bind(this);
【热门文章】
【热门文章】