关于js对象中两个函数互相调用,其中一个为定时器声明,定时器循环报错问题(记录一次尝试新写法的报错经历)附带无缝轮播图代码(详细的可以看下一个博)

先上代码吧(是想把之前写的的轮播图演示重构一下),注意timer这个有问题的方法:

var obj = {
    sleepTime: 2000,//轮播延时
    cont: 0,//第几张
    step: -500,//步距
    state: true,//左为false,右为true
    origin: document.getElementsByClassName('main-img')[0],//拿到全部图片的父级
    btnLeft: document.getElementsByClassName('btn')[0],
    btnRight: document.getElementsByClassName('btn')[1],
    init: function () {//主函数
        this.timer();
        this.click();
    },
    move: function (origin) {//移动
        this.state == true ? this.cont++ : this.cont--;
        clearInterval(timer1);
        origin.style.transform = 'translate3d(' + this.cont * this.step + 'px,0px,0px)';
        origin.style.transitionDuration = '0.3s';
        this.sleepTime = 2000;
        this.timer();
        if (this.cont > 4 && this.state == true) {
            this.change(origin, 0);
        };
        if (this.cont < 0 && this.state == false) {
            this.change(origin, 4);
        };
    },
    change: function (origin, cont) {//特殊处理
        clearInterval(timer1);
        this.cont = cont;
        origin.style.transitionDuration = '0s';
        origin.style.transform = 'translate3d(' + this.cont * this.step + 'px,0px,0px)';
        this.sleepTime = 50;
        this.timer();
    },
    timer: function () {//计时器
        timer1 = setInterval(function () {
            this.move(obj.origin);
            this.state = true;
        }, this.sleepTime)
    },
    click: function () {
        obj.btnLeft.onclick = function () {//向左
            obj.state = false;
            obj.move(obj.origin)
        };
        obj.btnRight.onclick = function () {//向右
            obj.state = true;
            obj.move(obj.origin)
        };
    }
}
obj.init();

    报错信息是这样的:move is not a function.当即想到一个问题,就是move的声明有问题,或者在timer中无法访问我定义的move,实验几次之后才发现是这个问题,定时器定义后执行环境就不是在对象中了,这也就访问不到move()了,那么只需要把定时器定时器中的this全部改成obj就可以了。

这种写法方便管理代码,不过还是需要谨慎使用。后续还需要深入学习才能避免在简单事情上经常犯错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值