<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body><script type="text/javascript" src='js/jquery-1.9.1.js'></script>
<script type="text/javascript">
(function() {
function container() {
this.current = 0;
this.max = 5;
this.loop;
this.start = true;
}container.prototype.play = function() {
if (this.start) {
this.start = false;
this.loop = setInterval(this.showNext, 1500);
}
};
container.prototype.showNext = function() {
if(this.current < this.max) {
this.current++;
}
console.log(this.current);
};
var ex = new container();
ex.play();
})();
</script>
</body>
</html>this.current为什么会返回未定义呢 jqueryjavascript

解决方案 »

  1.   

    this.loop = setInterval($.proxy(this,"showNext"), 1500);
      

  2.   

    通过setInterval(this.showNext, 1500)后 this已经指向为window
    container.prototype.play = function() {
        var that = this;
        if (this.start) {
            this.start = false;
            this.loop = setInterval(function(){
                that.showNext();
            }, 1500);
        }
    };container.prototype.showNext = function() {
        if(this.current < this.max) {
            this.current++;
        }
        console.log(this.current);
    };