JavaScript 帮忙看下这段程序为会返回未定义?

dxcqcv · 2013年10月06日 · 最后由 Pitt 回复于 2013年10月07日 · 2746 次阅读
<!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 为什么会返回未定义呢

作用域的问题,你可以在 container 函数定义 that = this, 然后在其他地方调用 that.current

#1 楼 @allenwei 能请教下为什么会这样吗?明明在 prototype 里面,为什么 this 不代表 container

this.current 中的 this 是调用 showNext 这个函数的对象,而这个函数是在 setInterval 中调用的,所以这个对象应该不是 container 的 instance,于是这里是 undefined。

this.loop = setInterval(this.showNext, 1500);

修改成

this.loop = setInterval(this.showNext.bind(this), 1500);

#4 楼 @Pitt 之前我用过 call,没效果,bind 却可以,奇怪,谢谢哈

#5 楼 @dxcqcv bind 简单说就是以参数为调用者,调用那个函数,所以函数内的 this 就是参数里指定的对象

@dxcqcv setInterval 的第一個參數是一個 function object,而不是 call 那個 function,所以 bind 在這裡是延遲綁定。call 肯定沒有效果的。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号